[英]How to avoid bug if geocoder sends me empty array when retrieving country of user (Rails 4/geocoder)
我正在構建每日交易Rails應用
我只向用戶顯示我與他聯系的國家/地區的交易,這要歸功於geocoder gem。
我不知道如果Geocoder無法(由於任何原因)無法檢索該國家並發送一個空數組,將會發生什么事情,就像我認為它在發送ip失敗時所做的那樣(請參閱https://github.com/alexreisner/geocoder#error-處理 )
class StaticPagesController < ApplicationController
def home
@deals = deal_in_user_country.featured_on_hp
respond_to do |format|
format.html # home.html.erb
end
end
# create a scope to filter the deals that meet the user's country
def deal_in_user_country
Deal.where(country: set_location_by_ip_lookup.country || 'United States') # if geocoder gets pb then default = US version
end
end
end
如您所見,我嘗試使用||。 並放置“美國”,但我認為它不會起作用。 我認為,如果Geocoder發送空數組,則set_location_by_ip_lookup = [],然后set_location_by_ip_lookup.country將生成錯誤,對嗎?
當地址解析器發送空數組時,應如何避免出現錯誤?
有關信息(如果有幫助的話),這是我如何將國家/地區設置為關注國家/國家
module CountrySetter
extend ActiveSupport::Concern
included do
before_filter :set_location_by_ip_lookup
end
def set_location_by_ip_lookup
if Rails.env.development? or Rails.env.test?
Geocoder.search(request.remote_ip).first
else #in production
request.location
end
end
end
如果地址解析器始終返回至少一個空數組,則您的代碼應該沒問題(但我不會命名此方法集為set_
因為它沒有設置任何內容)
嘗試irb
{a: [:d].first || :b}
=> {:a=>:d}
{a: [].first || :b}
=> {:a=>:b}
但是我會把這放在旁白中以使其清楚
Deal.where(country: (set_location_by_ip_lookup.country || 'United States'))
Gecodoer.search
不應Gecodoer.search
異常,否則它將被命名為Geocoder.search!
根據未成文的紅寶石慣例。 我會通過插入互聯網連接仔細檢查一下,看看會發生什么
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.