Skip to content

Instantly share code, notes, and snippets.

@tengla
Created January 17, 2012 12:21
Show Gist options
  • Save tengla/1626481 to your computer and use it in GitHub Desktop.
Save tengla/1626481 to your computer and use it in GitHub Desktop.
Some meta-progging example in Ruby
class Person
@people = []
@@id = 0
attr_accessor :id, :name, :age
def initialize(args)
@id = (@@id += 1)
@name = args[:name]
@age = args[:age]
end
def to_params
"?name=#{name}&age=#{age}"
end
class << self
def create(args)
@people << Person.new(args)
@people.last
end
def find(id)
@people.find{|person| person.id == id}
end
def find_by(attribute,value)
@people.select{|person| person.instance_variable_get("@#{attribute}") == value }
end
def method_missing(method_name,*args,&block)
if method_name.to_s.match(/find_by_(\w+)/)
method_name.to_s.match(/find_by_(\w+)/)
attribute = Regexp.last_match(1)
find_by(attribute,args.shift)
else
super
end
end
end
end
Person.create(:name => "Thomas", :age => 38)
Person.create(:name => "Espen", :age => 19)
p Person.find_by_name("Espen")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment