2009-07-17 63 views
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 

回答

5

怎麼樣以下

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 
+1

我忘記了`Address.new`可以採取塊。非常好! – 2009-07-17 15:58:13

相關問題