Created
March 2, 2012 10:33
-
-
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
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
# 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