Created
December 10, 2012 09:56
-
-
Save kirel/4249676 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module ArrayInquirer | |
def method_missing method, *args | |
begin | |
select { |elem| elem.send :"#{method}?", *args } | |
rescue NoMethodError | |
super method, *args | |
end | |
end | |
end | |
if __FILE__ == $0 | |
# Test cases should suffice as documentation | |
require 'test/unit' | |
class TestArrayInquirer < Test::Unit::TestCase | |
def test_it | |
assert_equal [nil,true].extend(ArrayInquirer).nil, [nil] | |
assert_equal [0,1,0].extend(ArrayInquirer).zero, [0,0] | |
assert_equal (0..10).extend(ArrayInquirer).even, [0,2,4,6,8,10] | |
end | |
def test_fail | |
assert_raise(NoMethodError) { [nil,true].extend(ArrayInquirer).foobar } | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module ObjectInquirer | |
def method_missing method, *args | |
begin | |
case method.to_s | |
when /^(.*)_is\?$/ | |
name = Regexp.last_match[1] | |
send(name) == args.first | |
else | |
super method, *args | |
end | |
rescue NoMethodError | |
super method, *args | |
end | |
end | |
end | |
if __FILE__ == $0 | |
# Test cases should suffice as documentation | |
require 'test/unit' | |
class Foo | |
include ObjectInquirer | |
attr_accessor :bar | |
end | |
class TestObjectInquirer < Test::Unit::TestCase | |
def setup | |
@foo = Foo.new | |
@foo.bar = 'baz' | |
end | |
def test_it | |
assert @foo.bar_is?('baz') | |
assert !@foo.bar_is?('cuux') | |
end | |
def test_fail | |
assert_raise(NoMethodError) { @foo.cuux_is?('the shizzle') } | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment