使用符号输入调用 class 方法

Call class method with symbol input

我有一个class方法:

class CountryCodes
  def self.country_codes
    { AF: "Afghanistan",
    AL: "Albania",
    ... }
  end
end

我有一个创建城市的 rake 任务,其中 country_code 类似于 "AF"。我希望它通过调用 class 方法并引用键值对来用 "Afghanistan" 替换 "AF"。

将 country_code 设置为类似于 "AF" 的当前功能是:

city = City.create do |c|
   c.name = row[:name] 
   c.country_code = row[:country_code] # sets country_code to be like "AF"
end

我可以通过调用 puts CountryCodes.country_codes[:AF] 手动检索 "Afghanistan"。通过结合这些策略,我(错误地)认为我可以:

city = City.create do |c|
   c.name = row[:name] 
   c.country_code = CountryCodes.country_code[:row[:country_code]] #obviously, this failed
end

我运行这个时候出现的故障是:

rake aborted! TypeError: no implicit conversion of Symbol into Integer

如何使用 row[:country_code] 的动态输入正确调用 CountryCodes.country_code class 方法?

由于CountryCodes.country_code有符号的散列,引用时需要调用符号。例如:country_code["AF"]country_code[:AF] 不同。

要更正此问题,请使用 Ruby 的 to_sym:

将字符串 row[:country_code] 转换为符号
city = City.create do |c|
   c.name = row[:name] 
   c.country_code = CountryCodes.country_code[row[:country_code].to_sym]  # < .to_sym
end

由于我看不到您的架构,我的回答还假设 country_code 是您的 City 模型中的 String(不是整数。)

认真回答:

使用country_codeGem! https://github.com/stefanpenner/country_select https://github.com/hexorx/countries https://github.com/alexrabarts/iso_country_codes

I18n 准备好等等