Class: Mws::Serializer
- Inherits:
-
Object
- Object
- Mws::Serializer
- Defined in:
- lib/mws/serializer.rb
Class Method Summary collapse
Instance Method Summary collapse
- #hash_for(node, context) ⇒ Object
-
#initialize(exceptions = {}) ⇒ Serializer
constructor
A new instance of Serializer.
- #xml_for(name, data, builder, context = nil) ⇒ Object
Constructor Details
#initialize(exceptions = {}) ⇒ Serializer
Returns a new instance of Serializer.
29 30 31 32 33 34 35 |
# File 'lib/mws/serializer.rb', line 29 def initialize(exceptions={}) @xml_exceptions = exceptions @hash_exceptions = {} exceptions.each do | key, value | @hash_exceptions[value.to_sym] = key end end |
Class Method Details
.leaf(name, parent, value, attributes) ⇒ Object
18 19 20 21 22 23 24 25 26 27 |
# File 'lib/mws/serializer.rb', line 18 def self.leaf(name, parent, value, attributes) if parent parent.send(name, value, attributes) parent.doc.root.to_xml else Nokogiri::XML::Builder.new do | xml | xml.send(name, value, attributes) end.doc.root.to_xml end end |
.tree(name, parent, &block) ⇒ Object
7 8 9 10 11 12 13 14 15 16 |
# File 'lib/mws/serializer.rb', line 7 def self.tree(name, parent, &block) if parent parent.send(name, &block) parent.doc.root.to_xml else Nokogiri::XML::Builder.new do | xml | xml.send(name, &block) end.doc.root.to_xml end end |
Instance Method Details
#hash_for(node, context) ⇒ Object
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
# File 'lib/mws/serializer.rb', line 55 def hash_for(node, context) elements = node.elements() return node.text unless elements.size > 0 res = {} elements.each do | element | name = @hash_exceptions[element.name.to_sym] || Utils.underscore(element.name).to_sym path = path_for name, context content = instance_exec element, path, &method(:hash_for) if res.include? name res[name] = [ res[name] ] unless res[name].instance_of? Array res[name] << content else res[name] = content end end res end |
#xml_for(name, data, builder, context = nil) ⇒ Object
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
# File 'lib/mws/serializer.rb', line 37 def xml_for(name, data, builder, context=nil) element = @xml_exceptions[name.to_sym] || Utils.camelize(name) path = path_for name, context if data.respond_to? :keys builder.send(element) do | b | data.each do | key, value | xml_for(key, value, builder, path) end end elsif data.respond_to? :each data.each { |value| xml_for(name, value, builder, path) } elsif data.respond_to? :to_xml data.to_xml element, builder else builder.send element, data end end |