Instantiate a new instance of the class into which we are included and populate that instance’s attributes given the provided Hash. Key names in the Hash should map to attribute names on the model.
# File lib/facebooker/model.rb, line 17 def from_hash(hash) instance = new(hash) yield instance if block_given? instance end
or a Hash which will be used to populate a new instance of ::klass::.
# File lib/facebooker/model.rb, line 54 def hash_settable_accessor(symbol, klass) attr_reader symbol hash_settable_writer(symbol, klass) end
or a list of Hashes which will be used to populate a new instance of ::klass::.
# File lib/facebooker/model.rb, line 68 def hash_settable_list_accessor(symbol, klass) attr_reader symbol hash_settable_list_writer(symbol, klass) end
# File lib/facebooker/model.rb, line 73 def hash_settable_list_writer(symbol, klass) define_method("#{symbol}=") do |list| instance_variable_set("@#{symbol}", list.map do |item| item.kind_of?(Hash) ? klass.from_hash(item) : item end) end end
# File lib/facebooker/model.rb, line 59 def hash_settable_writer(symbol, klass) define_method("#{symbol}=") do |value| instance_variable_set("@#{symbol}", value.kind_of?(Hash) ? klass.from_hash(value) : value) end end
# File lib/facebooker/model.rb, line 81 def id_is(attribute) (file, line) = caller.first.split(':') class_eval(" def #{attribute}=(value) @#{attribute} = value.to_i end attr_reader #{attribute.inspect} alias :id #{attribute.inspect} alias :id= #{"#{attribute}=".to_sym.inspect} ", file, line.to_i) end
Create a standard attr_writer and a #populating_attr_reader
# File lib/facebooker/model.rb, line 25 def populating_attr_accessor(*symbols) attr_writer(*symbols) populating_attr_reader(*symbols) end
Create a reader that will attempt to populate the model if it has not already been populated
# File lib/facebooker/model.rb, line 32 def populating_attr_reader(*symbols) symbols.each do |symbol| define_method(symbol) do populate unless populated? instance_variable_get("@#{symbol}") end end end
# File lib/facebooker/model.rb, line 41 def populating_hash_settable_accessor(symbol, klass) populating_attr_reader symbol hash_settable_writer(symbol, klass) end
# File lib/facebooker/model.rb, line 46 def populating_hash_settable_list_accessor(symbol, klass) populating_attr_reader symbol hash_settable_list_writer(symbol, klass) end