Report abuse


			
# In reference to http://www.devchix.com/2007/05/25/ruby-dry-up-your-enumerations/
# Examples by Susan Potter [http://susanpotter.net]

# Framework code...

class ProxyBase
  attr_accessor :collection

  def initialize(collection)
    @collection = collection
  end
end

class AnyProxy < ProxyBase
  def method_missing(sym, *args)
    @collection.each do |item|
      return true if item.send(sym, *args)
    end
  end
end

class AllProxy < ProxyBase
  def method_missing(sym, *args)
    @collection.each do |item|
      return false unless item.send(sym, *args)
    end
  end
end

module LinkingVerbMixin
  def self.included(base)
    base.extend(ClassMethods)
  end

  module ClassMethods
    def any(collection)
      AnyProxy.new(collection)
    end

    def all(collection)
      AllProxy.new(collection)
    end
  end
end

class Are
  include LinkingVerbMixin
end

class Do
  include LinkingVerbMixin
end

# Application code...

class Stooge
  attr_accessor :name, :bald

  def initialize(name, bald)
    @name = name
    @bald = bald
  end

  def bald?
    @bald
  end
end

mo = Stooge.new("Mo", true)
larry = Stooge.new("Larry", false)
curly = Stooge.new("Curly", false)
stooges = [mo, larry, curly]

Are.all(stooges).bald?
Are.any(stooges).bald?

# This can be extended further to do stuff like Do.all(stooges).have(:name, :eql?, "Mo"), etc.