2
我的Address
類有一個geocode
類方法,該方法返回從地理編碼方法參數(如果地理編碼導致精確匹配,數組將具有一個元素)派生的地址對象數組。使GeoKit與我的地址類很好地配合
關於編寫此方法的一個煩人的部分是將GeoKit地址對象轉換爲我的地址對象(例如,「street_address」 - >「address1」)。有一個更好的方法嗎?
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
我忘記了`Address.new`可以採取塊。非常好! – 2009-07-17 15:58:13