Created
September 27, 2010 14:55
-
-
Save valo/599163 to your computer and use it in GitHub Desktop.
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
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