Sha256: 951d9e8356d316c9cc26965625b5a8d81ac8caec562565db152f69068d01d6da

Contents?: true

Size: 1.78 KB

Versions: 4

Compression:

Stored size: 1.78 KB

Contents

module RubyPsigate
  
  class InvalidHashError < ArgumentError; end;
  
  class Serializer
    # Initializes a new object with an inputted hash
    #
    # my_hash = { :something => "special" }
    # Serializer.new(my_hash)
    def initialize(input_hash, options = { :header => false })
      raise InvalidHashError, "Input parameters does not contain a hash!" unless input_hash.is_a?(Hash)
      @input_hash = input_hash
      @header = options[:header]
    end
    
    # 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
    def to_xml
      @builder = Builder::XmlMarkup.new
      @builder.instruct! if @header
      build_level(@input_hash)
      @builder.target!
    end
    
    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
    
    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
  end
  
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
ruby_psigate-0.7.8 lib/ruby_psigate/serializer.rb
ruby_psigate-0.7.7 lib/ruby_psigate/serializer.rb
ruby_psigate-0.7.6 lib/ruby_psigate/serializer.rb
ruby_psigate-0.7.5 lib/ruby_psigate/serializer.rb