Skip to content

Instantly share code, notes, and snippets.

@h3h
Created March 10, 2011 00:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save h3h/863325 to your computer and use it in GitHub Desktop.
Save h3h/863325 to your computer and use it in GitHub Desktop.
You know, for objects.
require 'active_support/core_ext/hash/keys'
# Intended as an extension for an ActiveRecord model. It allows construction
# of a valid ActiveRecord object from a Hash, including proper handling of
# the :id attribute.
module ActiveRecordFromHash
def from_hash(hsh)
hsh = hsh.symbolize_keys
self.new.tap do |obj|
# use []= to skip AR setter checks for :id
obj[:id] = hsh.delete(:id)
# use regular method setters for all other attributes
hsh.each do |k,v|
obj.send(:"#{k}=", v)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment