Created
July 20, 2009 22:03
-
-
Save thilo/150940 to your computer and use it in GitHub Desktop.
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
# fixes deserialization from xml with nested associations | |
# based on http://www.xcombinator.com/2008/08/11/activerecord-from_xml-and-from_json-part-2/ | |
module ActiveRecord #:nodoc: | |
module Serialization | |
def from_hash( hash ) | |
h = hash.dup | |
h.each do |key,value| | |
case value.class.to_s | |
when 'Array' #collection | |
self.send(key).map! { |e| self.class.reflect_on_association(key.to_sym ).klass.new.from_hash e } | |
when /\AHash(WithIndifferentAccess)?\Z/ #single object | |
if self.send(key).nil? #new object | |
self.send("#{key}=", self.class.reflect_on_association(key.to_sym).klass.new.from_hash(value)) | |
else #existing object | |
self.send(key).from_hash(value) | |
end | |
else | |
self.send("#{key}=", value) | |
end | |
end | |
self | |
end | |
def from_json( json ) | |
from_hash safe_json_decode( json ) | |
end | |
# The xml has a surrounding class tag (e.g. ship-to), | |
# but the hash has no counterpart (e.g. 'ship_to' => {} ) | |
def from_xml( xml ) | |
from_hash begin | |
Hash.from_xml(xml).values.first | |
rescue ; {} end | |
end | |
end # class Base | |
end # module ActiveRecord | |
### Global functions ### | |
# JSON.decode, or return {} if anything goes wrong. | |
def safe_json_decode( json ) | |
return {} if !json | |
begin | |
ActiveSupport::JSON.decode json | |
rescue ; {} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment