#!/usr/bin/env ruby # 9/2/2009 # Carlan Calazans (carlancalazans at gmail.com) require 'net/http' require 'rexml/document' class CepLivre URL_CEP_LIVRE = 'http://ceplivre.pc2consultoria.com/index.php?module=cep&formato=xml&cep=' FIELDS = %w(tipo_logradouro logradouro bairro cidade estado_sigla) def initialize(cep) @cep = cep get_data end def to_array @result = [] process_a end def to_hash @result = {} process_h end private def get_data @data = Net::HTTP.get_response(URI.parse("#{URL_CEP_LIVRE}#{@cep}")) raise "Connection error." unless @data.kind_of?(Net::HTTPSuccess) @xml = REXML::Document.new(@data.body) end def process_a FIELDS.each do |f| field = REXML::XPath.match(@xml, "//#{f}").first @result << field.text end @result end def process_h FIELDS.each do |f| field = REXML::XPath.match(@xml, "//#{f}").first @result[f] = field.text end @result end end # Array puts CepLivre.new("29040-470").to_array # Hash puts CepLivre.new("29040-470").to_hash