I find a frequent scenario in Ruby on Rails code base. A local hash variable is assigned a partial subset of an ActiveRecord object, or worse the variable gets the entire AR object. And may be you don’t already do it the way I have seen it, but its still worth discussing, being as frequent a requirement as it is.
1. If we want to assign an entire AR object to a local hash:
A direct assignment is possible with “attributes”
local_hash = session_user.attributes
the ‘local_hash’ now has an attribute-value hash of the session_user object, an ActiveRecord object of model User ]
2. If we need the local_hash to have only a subset of the AR object attributes:
desired_keys = ['address' , 'zipcode' , 'city' , 'country']
local_array = session_user.attributes.select{|key,value| desired_keys.include?(key) }
local_hash = Hash[*local_array.flatten]
the ‘local_hash’ now has only the desired attribute values. This can easily be extended by simply adding more keys to ‘desired_keys’.
Instead of what I usually see,
local_hash = {
'address' => session_user.address,
'zipcode' => session_user.zipcode,
'city' => session_user.city,
'country' => session_user.country
}
What do you think of this snippet? Is there a shorter/smarter way of doing this? Think on!