Created
January 7, 2015 15:08
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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