Permalink
Browse files

added type validation to distance method so that seg.faults are preve…

…nted
  • Loading branch information...
1 parent 87da243 commit 86d03fe40942bee0d926bb1d47c5c1395af59797 @harbu harbu committed Dec 22, 2011
Showing with 45 additions and 13 deletions.
  1. +1 −1 Gemfile
  2. +10 −2 Gemfile.lock
  3. +23 −8 lib/levenshtein.rb
  4. +11 −0 spec/levenshtein_spec.rb
  5. +0 −2 spec/spec_helper.rb
View
@@ -3,6 +3,6 @@ source :rubygems
gem 'ffi'
group :test do
- gem 'rspec', '1.3.1'
+ gem 'rspec', '2.7.0'
gem 'jeweler'
end
View
@@ -1,19 +1,27 @@
GEM
remote: http://rubygems.org/
specs:
+ diff-lcs (1.1.3)
ffi (1.0.9)
git (1.2.5)
jeweler (1.6.4)
bundler (~> 1.0)
git (>= 1.2.5)
rake
rake (0.9.2)
- rspec (1.3.1)
+ rspec (2.7.0)
+ rspec-core (~> 2.7.0)
+ rspec-expectations (~> 2.7.0)
+ rspec-mocks (~> 2.7.0)
+ rspec-core (2.7.1)
+ rspec-expectations (2.7.0)
+ diff-lcs (~> 1.1.2)
+ rspec-mocks (2.7.0)
PLATFORMS
ruby
DEPENDENCIES
ffi
jeweler
- rspec (= 1.3.1)
+ rspec (= 2.7.0)
View
@@ -1,12 +1,27 @@
require 'ffi'
module Levenshtein
- extend FFI::Library
-
- # Try loading in order.
- library = File.dirname(__FILE__) + "/../ext/levenshtein/levenshtein"
- candidates = ['.bundle', '.so', '.dylib', ''].map { |ext| library + ext }
- ffi_lib(candidates)
-
- attach_function :distance, :levenshtein, [:string, :string], :int
+ class << self
+ extend FFI::Library
+
+ # Try loading in order.
+ library = File.dirname(__FILE__) + "/../ext/levenshtein/levenshtein"
+ candidates = ['.bundle', '.so', '.dylib', ''].map { |ext| library + ext }
+ ffi_lib(candidates)
+
+ def distance(str1, str2)
+ validate(str1)
+ validate(str2)
+ ffi_distance(str1, str2)
+ end
+
+ private
+ def validate(arg)
+ unless arg.kind_of?(String)
+ raise TypeError, "wrong argument type #{arg.class} (expected String)"
+ end
+ end
+
+ attach_function :ffi_distance, :levenshtein, [:string, :string], :int
+ end
end
@@ -19,4 +19,15 @@
Levenshtein.distance(w2, w1).should == d
end
end
+
+ it "should raise an error if either argument is nil" do
+ expect { Levenshtein.distance("", nil) }.to raise_error TypeError
+ expect { Levenshtein.distance(nil, "") }.to raise_error TypeError
+ end
+
+ it "should raise an error if either argument is something else than a string" do
+ expect { Levenshtein.distance("woah", /woah/) }.to raise_error TypeError
+ expect { Levenshtein.distance(5.3, "5.3") }.to raise_error TypeError
+ expect { Levenshtein.distance(Object.new, "Hello") }.to raise_error TypeError
+ end
end
View
@@ -1,3 +1 @@
-require 'spec'
-
require File.dirname(__FILE__) + "/../lib/levenshtein"

0 comments on commit 86d03fe

Please sign in to comment.