在 rake 任务中使用 lib/assets 中的哈希对象

Using hash object in lib/assets within a rake task

在我的 lib/assets/country_codes.rb 文件中:

# lib/assets/country_codes.rb

class CountryCodes
  country_codes = {
    AF: "Afghanistan",
    AL: "Albania",
    [...]
  }
end

在抽取任务中,我使用:

# lib/tasks/fetch_cities

require '/assets/country_codes'

city = City.create do |c|
      c.name = row[:name] 
      c.country_code = row[:country_code] # row[:country_code] in this case is like "AF"
end

我想补充c.country_codes.t。就像 "Afghanistan"。但是,它当前已添加,如上面的代码中所示,如 "AF"。

我想对平面文件执行查找,以便 "AF" 替换为 "Afghanistan"。

我目前的问题是我在引用散列对象时遇到了问题。当我尝试访问

puts "#{CountryCodes.country_codes.AF}"

我返回:

undefined method `country_codes' for CountryCodes:Class

如何访问 lib/assets/country_codes.rb 文件中的哈希对象?

将其更改为 class 方法,例如:

class CountryCodes

  def self.country_codes 
    # This is a class method, you call it on the class.
    # Example:
    # CountryCodes.country_codes[:AF]
    { AF: "Afghanistan",
      AL: "Albania" }
  end

  def country_codes
    # This is an instance method. You call it on an instance. 
    # It just runs the class method, right now.
    # You might use it like this:
    # c = CountryCodes.new
    # c.country_codes
    self.class.country_codes
  end

end

您需要像这样引用它:

puts CountryCodes.country_codes[:AF]