Created
February 22, 2013 02:56
-
-
Save burtlo/5010400 to your computer and use it in GitHub Desktop.
Example of using Ruby's Meta-programming to build finders and reduce duplication.
This file contains hidden or 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
module HasAttributes | |
def attribute(name) #id | |
# With the given name add an instance method with that name | |
# define_method(name) do | |
# instance_variable_get("@#{name}") | |
# end | |
attr_reader name | |
# With the given name add a class method find_by_NAME | |
define_singleton_method("find_by_#{name}") do |value| | |
all.find_all do |object| | |
object.send(name) == value | |
end | |
end | |
end | |
end | |
class Customer | |
extend HasAttributes | |
def self.all | |
# go load from the csv | |
[] | |
end | |
attribute :id | |
attribute :first_name | |
attribute :last_name | |
end | |
class Merchant | |
extend HasAttributes | |
def self.all | |
# go load from the csv | |
[] | |
end | |
attribute :id | |
attribute :name | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment