Let\'s say that I have a User
model with attributes :id, :first_name, :last_name, and :email
. In my application, guest users shouldn\'t see User\
Had a requirement like this but wanted something more generic that would just gather a list of method names and values from a model (including attributes). So, I added this method to my model:
def attributes_from_keys(*keys)
keys.inject({}) do |hash_to_return, key|
hash_to_return.merge(key => send(key))
end
end
Then, call this method with:
MyModel.find(1).attributes_from_keys(:id, :name, :age)
returns
{id: 1, name: 'Lawrence', age: 23}