Skip to content

Instantly share code, notes, and snippets.

@kirel
Created December 10, 2012 09:56
Show Gist options
  • Save kirel/4249676 to your computer and use it in GitHub Desktop.
Save kirel/4249676 to your computer and use it in GitHub Desktop.
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
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