Skip to content

Instantly share code, notes, and snippets.

@nakajima
Created March 20, 2009 07:48
Show Gist options
  • Save nakajima/82273 to your computer and use it in GitHub Desktop.
Save nakajima/82273 to your computer and use it in GitHub Desktop.
module Enumerable
class Evaluator
instance_methods.each { |s| undef_method(s) unless s.to_s =~ /__/ }
def initialize(enum, invoke=nil)
@enum = enum
@invoke = invoke
end
def not
@negate = true
self
end
def method_missing(sym, *args, &blk)
if @invoke
res = @enum.send(@invoke) { |i| i.send(sym, *args, &blk) }
@negate ? !res : res
else
@invoke = sym.to_s + '?'
self
end
end
end
def not
Evaluator.new(self).not
end
def any
Evaluator.new(self, :any?)
end
def all
Evaluator.new(self, :all?)
end
def every
Evaluator.new(self, :each)
end
end
require 'bacon'
describe "any" do
it "provides proxy" do
[nil, :foo].any.nil?.should.be.true
[:foo, :bar].any.nil?.should.be.false
end
it "takes args" do
[nil, :bar].any.is_a?(Symbol).should.be.true
[nil, 'bar'].any.is_a?(Symbol).should.be.false
end
it "can be negated" do
[nil, :bar].not.any.kind_of?(Symbol).should.be.false
[nil, 'foo'].not.any.kind_of?(Symbol).should.be.true
end
end
describe "all" do
it "provides proxy" do
[nil, nil].all.nil?.should.be.true
[nil, :bar].all.nil?.should.be.false
end
it "takes args" do
[:foo, :bar].all.is_a?(Symbol).should.be.true
[nil, :foo].all.is_a?(Symbol).should.be.false
end
it "can be negated" do
[:foo, :bar].not.all.kind_of?(Symbol).should.be.false
[nil, :foo].not.all.kind_of?(Symbol).should.be.true
end
end
describe "every" do
it "provides proxy" do
a = ['foo', 'bar']
a.every.upcase!
a.should == ['FOO', 'BAR']
end
it "takes args and block" do
a = ['foo', 'bar']
a.every.gsub!(/^./) { |m| m.upcase }
a.should == ['Foo', 'Bar']
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment