Skip to content

Instantly share code, notes, and snippets.

@jgaskins
Created March 2, 2012 10:33
Show Gist options
  • Save jgaskins/1957596 to your computer and use it in GitHub Desktop.
Save jgaskins/1957596 to your computer and use it in GitHub Desktop.
Experiment to allow users to use Enumerable-style select on mappers to retrieve the objects they want from the DB
# Attribute class would go into the DB layer
class Attribute
def initialize name
@name = name
end
# For attribute == value
# For demo purposes, I didn't feel like implementing other comparators
def == value
{ @name => value }
end
end
# Returned by the #select method on mappers
class Selection
def initialize mapper
@mapper = mapper
end
def method_missing missing_method
raise "That's not an attribute: #{missing_method}" unless @mapper.attributes.include?(missing_method)
Attribute.new missing_method
end
end
class UserMapper
attr_reader :attributes
def initialize
@attributes = [:name, :foo]
end
def select &block
Selection.new(self).instance_eval &block
end
end
p UserMapper.new.select{ |user| user.name == 'Jamie' }
# => { :name => 'Jamie' } Yaaaay!
p UserMapper.new.select{ |user| user.name == 'Jamie' && user.foo == 'bar' }
# => { :foo => 'bar' } Booo! No mention at all of the first term.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment