Skip to content

Commit

Permalink
added helper Kernel#extract to work with method overloading (useful f…
Browse files Browse the repository at this point in the history
…or complicated APIs like View#find)
  • Loading branch information
Oleg Andreev committed May 1, 2008
1 parent 008157e commit 8806a20
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
28 changes: 28 additions & 0 deletions lib/strokedb/core_ext/kernel.rb
Expand Up @@ -15,4 +15,32 @@ def require_one_of(*args)
end

end

# Helps to extract arguments for an overloaded methods:
# def some_method(*args)
# store, name, options = extract(Store, String, Hash, args)
# end
#
# This method tries to extract arguments according to their type.
# If the correct type is missing, var is set to nil.
# If some of the input arguments are not matched, ArgumentError is raised.
#
def extract(*template_and_args)
args = template_and_args.pop
result = []

args.each do |a|
unless while t = template_and_args.shift
if t === a
result << a
break(true)
else
result << nil
end
end
raise ArgumentError, "Unexpected argument #{a.inspect} is passed!"
end
end
result + template_and_args.map{ nil }
end
end
42 changes: 42 additions & 0 deletions spec/lib/strokedb/core_ext/extract_spec.rb
@@ -0,0 +1,42 @@
require File.dirname(__FILE__) + '/spec_helper'

describe "Kernel#extract" do

it "should correctly extract various arguments" do
extract(Regexp, String, Hash, [ ]).should == [nil, nil, nil]

extract(Regexp, String, Hash, [/a/ ]).should == [/a/, nil, nil]
extract(Regexp, String, Hash, [ "a" ]).should == [nil, "a", nil]
extract(Regexp, String, Hash, [ {1=>2}]).should == [nil, nil, {1=>2}]

extract(Regexp, String, Hash, [//, "" ]).should == [//, "", nil]
extract(Regexp, String, Hash, [//, {}]).should == [//, nil, {} ]
extract(Regexp, String, Hash, [ "", {}]).should == [nil, "", {}]

extract(Regexp, String, Hash, [//, "", {}]).should == [//, "", {} ]
end

it "should raise ArgumentError when wrong arguments are passed" do

bad_case(Regexp, String, Hash, [123])
bad_case(Regexp, String, Hash, ["", //])
bad_case(Regexp, String, Hash, [{}, ""])
bad_case(Regexp, String, Hash, [true])
bad_case(Regexp, String, Hash, [false])
bad_case(Regexp, String, Hash, [//,false])
bad_case(Regexp, String, Hash, [nil])
bad_case(Regexp, String, Hash, ["", nil])
bad_case(Regexp, String, Hash, [nil, nil])
bad_case(Regexp, String, Hash, [{}, {}])
bad_case(Regexp, String, Hash, [//, //])
bad_case(Regexp, String, Hash, [ [] ])
bad_case(Regexp, String, Hash, [Object.new])
bad_case(Regexp, String, Hash, [Object.new, Object.new])

end

def bad_case(*args)
lambda { extract(*args) }.should raise_error(ArgumentError)
end

end

0 comments on commit 8806a20

Please sign in to comment.