Sha256: f92999f2e2f82cf80fe56decff6dab897a8b83fb5629430f1f005d4bc84e6fff

Contents?: true

Size: 1.2 KB

Versions: 5

Compression:

Stored size: 1.2 KB

Contents

require 'ox'

module Correios
  module CEP
    class Parser
      ADDRESS_MAP = {
        'end'          => :address,
        'bairro'       => :neighborhood,
        'cidade'       => :city,
        'uf'           => :state,
        'cep'          => :zipcode,
        'complemento'  => :complement,
        'complemento2' => :complement2,
      }.freeze

      def address(xml)
        doc = Ox.parse(xml)

        return_node = find_node(doc.nodes, 'return')
        return {} if return_node.nil?

        address = {}
        return_node.nodes.each do |element|
          address[ADDRESS_MAP[element.name]] = text_for(element) if ADDRESS_MAP[element.name]
        end

        join_complements(address)
        address
      end

      private

      def find_node(nodes, name)
        node = nodes.last
        return nil unless node.is_a?(Ox::Element)
        return node if node.nil? || node.name == name

        find_node(node.nodes, name)
      end

      def text_for(element)
        element.text.to_s.force_encoding(Encoding::UTF_8)
      end

      def join_complements(address)
        address[:complement] += " #{address.delete(:complement2)}"
        address[:complement].strip!
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
correios-cep-0.6.2 lib/correios/cep/parser.rb
correios-cep-0.6.1 lib/correios/cep/parser.rb
correios-cep-0.6.0 lib/correios/cep/parser.rb
correios-cep-0.5.1 lib/correios/cep/parser.rb
correios-cep-0.5.0 lib/correios/cep/parser.rb