Skip to content

Instantly share code, notes, and snippets.

@breckenedge
Created January 7, 2015 15:08
Show Gist options
  • Save breckenedge/f38bb615b21d38ed7c9a to your computer and use it in GitHub Desktop.
Save breckenedge/f38bb615b21d38ed7c9a to your computer and use it in GitHub Desktop.
For converting an object to a hash (tired of writing one-time-use presenters for JSON, needed quick method)
# Calls attributes on obj, returning results as a hash. Be careful to never
# run this code with user-provided attributes.
#
# Example:
# as_hash_from_object(user, ["first_name", "last_name", "account.name"])
# #=> {"first_name" => "Aaron", "last_name" => "Breckenridge", "account.name" => "System Root"}
def as_hash_from_object(object, attribs)
attribs.each_with_object({}) do |attrib, hash|
hash[attrib] = attrib.split('.').reduce(object) { |o, i| o.respond_to?(i) ? o.send(i) : nil }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment