Sha256: b6c695ae5087bbd9a4f932ab58304a794e9ac2992e5d248cbe4eca57abb2976c
Contents?: true
Size: 1.74 KB
Versions: 5
Compression:
Stored size: 1.74 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 @builder.tag!(key) { |level| value.is_a?(Hash) ? build_level(value) : level.text!(value.to_s) } else build_level_from_array_element(value) end end end def build_level_from_array_element(input_array) input_array.each do |element| @builder.tag!(:Item) { 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
5 entries across 5 versions & 1 rubygems