Skip to content

Instantly share code, notes, and snippets.

@valo
Created September 27, 2010 14:55
Show Gist options
  • Save valo/599163 to your computer and use it in GitHub Desktop.
Save valo/599163 to your computer and use it in GitHub Desktop.
module AttributeBuilder
def initialize(attrs = {})
attrs ||= {}
attrs.each do |key, value|
self.send("#{key}=", value)
end
end
end
module MemberBuilder
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def buildable_member(member, clazz)
define_method "#{member}=" do |attr|
case attr
when clazz then instance_variable_set("@#{member}", attr)
else instance_variable_set("@#{member}", clazz.new(attr))
end
end
end
end
end
class Address
include AttributeBuilder
attr_accessor :street, :city
end
class Person
include AttributeBuilder
include MemberBuilder
attr_accessor :name, :gender, :address
buildable_member :address, Address
end
a = { :name => "Pencho", :gender => "M", :address => { :street => "Elm", :city => "Anaheim" }}
p = Person.new(a)
puts p.address.city
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment