Skip to content

Instantly share code, notes, and snippets.

@burtlo
Created February 22, 2013 02:56
Show Gist options
  • Save burtlo/5010400 to your computer and use it in GitHub Desktop.
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.
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