Skip to content

Commit

Permalink
fix: raises TypeError when input type is not string
Browse files Browse the repository at this point in the history
closes #24
  • Loading branch information
tonytonyjan committed Jan 4, 2019
1 parent e1b9add commit c146491
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 0 deletions.
2 changes: 2 additions & 0 deletions ext/jaro_winkler/jaro_winkler.c
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ VALUE distance(size_t argc, VALUE *argv, VALUE self,

rb_scan_args((int32_t)argc, argv, "2:", &s1, &s2, &opt);

Check_Type(s1, T_STRING);
Check_Type(s2, T_STRING);
Options c_opt = DEFAULT_OPTIONS;
if (TYPE(opt) == T_HASH) {
VALUE weight = rb_hash_aref(opt, ID2SYM(rb_intern("weight"))),
Expand Down
6 changes: 6 additions & 0 deletions lib/jaro_winkler/jaro_winkler_pure.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,12 @@ class InvalidWeightError < Error; end

class << self
def distance(str1, str2, options = {})
validate!(str1, str2)
_distance str1.codepoints.to_a, str2.codepoints.to_a, options
end

def jaro_distance(str1, str2, options = {})
validate!(str1, str2)
_jaro_distance str1.codepoints.to_a, str2.codepoints.to_a, options
end

Expand Down Expand Up @@ -125,5 +127,9 @@ def _jaro_distance(codes1, codes2, options = {})
m = similar_count / 10.0 + m if options[:adj_table]
(m / len1 + m / len2 + (m - t) / m) / 3
end

def validate!(str1, str2)
raise TypeError unless str1.is_a?(String) && str2.is_a?(String)
end
end
end
9 changes: 9 additions & 0 deletions test/tests.rb
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,15 @@ def test_encoding
assert_distance 1.0, "\xe8".force_encoding('iso8859-1'), 'è'
end

def test_raises_type_error
assert_raises(TypeError){ JaroWinkler.distance 'MARTHA', nil }
assert_raises(TypeError){ JaroWinkler.distance nil, 'MARTHA' }
assert_raises(TypeError){ JaroWinkler.distance nil, nil }
assert_raises(TypeError){ JaroWinkler.distance 'MARTHA', :non_string }
assert_raises(TypeError){ JaroWinkler.distance :non_string, 'MARTHA' }
assert_raises(TypeError){ JaroWinkler.distance :non_string, :non_string }
end

private

def assert_distance score, str1, str2, options={}
Expand Down

0 comments on commit c146491

Please sign in to comment.