Created
March 10, 2011 00:34
-
-
Save h3h/863325 to your computer and use it in GitHub Desktop.
You know, for objects.
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
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