forked from caelum/restfulie
/
unmarshalling.rb
91 lines (85 loc) · 2.36 KB
/
unmarshalling.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# module Hashi
# class CustomHash
# # uses_restfulie
# def initialize(h)
# @hash = h
# link = h['link']
# add_transitions([link]) if link.kind_of? Hash
# add_transitions(link) if link.kind_of? Array
# end
# end
# end
#
# module Jeokkarak
# module Base
# alias_method :old_from_hash_parse, :from_hash_parse
# def from_hash_parse(result,h,key,value)
# return old_from_hash_parse(result, h, key, value) if key!='link'
# link = h[key]
# result.add_transitions([link]) if link.kind_of? Hash
# result.add_transitions(link) if link.kind_of? Array
# end
# end
# end
module Restfulie
module Unmarshalling
# basic code from Matt Pulver
# found at http://www.xcombinator.com/2008/08/11/activerecord-from_xml-and-from_json-part-2/
# addapted to support links
def from_hash( hash )
h = {}
h = hash.dup if hash
links = nil
h.each do |key,value|
case value.class.to_s
when 'Array'
if key=="link"
links = h[key]
h.delete("link")
else
h[key].map! { |e| reflect_on_association(key.to_sym ).klass.from_hash e }
end
when /\AHash(WithIndifferentAccess)?\Z/
if key=="link"
links = [h[key]]
h.delete("link")
else
h[key] = reflect_on_association(key.to_sym ).klass.from_hash value
end
end
h.delete("xmlns") if key=="xmlns"
end
result = self.new h
if !(links.nil?) && self.include?(Restfulie::Client::Instance)
result.add_transitions(links)
end
result
end
end
end
module ActiveRecord
class Base
extend Restfulie::Unmarshalling
# acts_as_jeokkarak
def self.from_json(json)
from_hash(safe_json_decode(json).values.first)
end
# The xml has a surrounding class tag (e.g. ship-to),
# but the hash has no counterpart (e.g. 'ship_to' => {} )
def self.from_xml(xml)
hash = Hash.from_xml xml
head = hash[self.to_s.underscore]
result = self.from_hash head
return nil if result.nil?
result._came_from = :xml if self.include?(Restfulie::Client::Instance)
result
end
end
end
def safe_json_decode(json)
return {} if !json
begin
ActiveSupport::JSON.decode json
rescue ; {} end
end
# end of code based on Matt Pulver's