views:

240

answers:

1

My Address class has a geocode class method that returns an array of address objects derived from geocoding the method's parameter (if the geocoding results in an exact match, the array will have one element).

One annoying part about writing this method is translating the GeoKit address objects to my address objects (e.g., "street_address" -> "address1"). Is there a better way to do this?

class Address < ActiveRecord::Base
  def self.geocode(string)
    return nil if string.nil?

    results = Geokit::Geocoders::GoogleGeocoder.geocode(string)

    address_objects = Array.new

    results.all.each do |r|
      params = Hash.new

      params['address1'] = r.street_address
      params['city'] = r.city
      params['zipcode'] = r.zip
      params['state'] = State.find_by_abbr(r.state)
      params['country'] = Country.find_by_iso(r.country_code)

      new_address = Address.new(params)
      new_address.single_line_address = r.full_address

      address_objects << new_address    
    end

    return address_objects
  end
end
+5  A: 

What about the following

class Address < ActiveRecord::Base
  def self.geocode(string)
    return if string.nil?

    results = Geokit::Geocoders::GoogleGeocoder.geocode(string)
    results.all.map do |r|
      Address.new do |address|
        address.address1  = r.street_address
        address.city      = r.city
        address.zipcode   = r.zip
        address.state     = State.find_by_abbr(r.state)
        address.country   = Country.find_by_iso(r.country_code)
        address.single_line_address = r.full_address
      end
    end
  end
end
Simone Carletti
I had forgotten that `Address.new` can take a block. Very nice!
Horace Loeb