Brandon Harris | Populate Object Instance Variables From Hash

Populate Object Instance Variables From Hash

I recently needed to write a class in ruby that I wanted to behave similarly to an ActiveRecord based class, but without the database ties. Particularly, I wanted to do this:

1 r = Record.new({:attribute1 => "a", :attribute2 => "b"})

It’s not too hard to hard code a simple class with attributes that are defined by a Hash, but in the pursuit of elegance, I wanted it to be more generic. I pulled up this little snippet:

1   attributes.each do |k, v|
2     if k.include?("(")
3       multi_parameter_attributes << [ k, v ]
4     else
5       respond_to?(:"#{k}=") ? send(:"#{k}=", v) : raise(UnknownAttributeError, "unknown attribute: #{k}")
6     end
7   end

This is your most basic metaprogramming technique in ruby. Check if the object responds to the message, and if so, set it.

Below is all that I needed to accomplish my task:

1   def initialize(attributes={})
2     attributes.each do |k,v|
3       respond_to?(:"#{k}=") ? send(:"#{k}=", v) : raise(NoMethodError, "Unknown method #{k}, add it to the record attributes")
4     end
5   end

Tags

  • e (1)