Class: RubyPsigate::Serializer
- Inherits:
-
Object
- Object
- RubyPsigate::Serializer
- Defined in:
- lib/ruby_psigate/serializer.rb
Instance Method Summary collapse
- #build_level(hash_level) ⇒ Object
- #build_level_from_array_element(tag, input_array) ⇒ Object
-
#initialize(input_hash, options = { :header => false }) ⇒ Serializer
constructor
Initializes a new object with an inputted hash.
-
#to_xml ⇒ Object
Converts from a hash to a hierarchical XML.
Constructor Details
#initialize(input_hash, options = { :header => false }) ⇒ Serializer
Initializes a new object with an inputted hash
my_hash = { :something => “special” } Serializer.new(my_hash)
10 11 12 13 14 |
# File 'lib/ruby_psigate/serializer.rb', line 10 def initialize(input_hash, = { :header => false }) raise InvalidHashError, "Input parameters does not contain a hash!" unless input_hash.is_a?(Hash) @input_hash = input_hash @header = [:header] end |
Instance Method Details
#build_level(hash_level) ⇒ Object
33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/ruby_psigate/serializer.rb', line 33 def build_level(hash_level) raise InvalidHashError, "Need hash to build XML" unless hash_level.is_a?(Hash) for key, value in hash_level # If the element at this level is :Item, then we know that it will be an array unless key == :Item || key == :ItemInfo @builder.tag!(key) { |level| value.is_a?(Hash) ? build_level(value) : level.text!(value.to_s) } else tag = key build_level_from_array_element(tag, value) end end end |
#build_level_from_array_element(tag, input_array) ⇒ Object
48 49 50 51 52 53 54 55 56 57 |
# File 'lib/ruby_psigate/serializer.rb', line 48 def build_level_from_array_element(tag, input_array) input_array.each do |element| @builder.tag!(tag) { element.each_pair do |key, value| # @builder.tag!(key) { |level| level.text!(value) } @builder.tag!(key) { |level| value.is_a?(Hash) ? build_level(value) : level.text!(value) } end } end end |
#to_xml ⇒ Object
Converts from a hash to a hierarchical XML
An example:
Converts
> { :Something => “Hello World” }
to this:
> “<?xml version="1.0" encoding="UTF-8"?><Something>Hello World</Something>”
Can also handle nested hashes
26 27 28 29 30 31 |
# File 'lib/ruby_psigate/serializer.rb', line 26 def to_xml @builder = Builder::XmlMarkup.new @builder.instruct! if @header build_level(@input_hash) @builder.target! end |