2015-10-09 17 views
2

在我的lib /资产/ country_codes.rb文件:使用耙子任务中的LIB哈希对象/资产

# lib/assets/country_codes.rb 

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

在rake任务,我用:

# 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_code st它就像“阿富汗”。但是,它目前已添加,如上面的代码中所示,如“AF”。

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

我目前的问题是我只是在引用散列对象时遇到问题。

undefined method `country_codes' for CountryCodes:Class 

如何访问的lib /资产/ country_codes.rb文件中的哈希对象:当我尝试访问

puts "#{CountryCodes.country_codes.AF}" 

我有回来了?

回答

2

将其更改为一个类的方法,如:

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] 
+0

这看起来太棒了!一旦我确认就会批准答案!为什么'def self.country_codes'而不是'def country_codes'? –

+1

@ColeBittel在代码中添加了解释。 –

+0

当我们将代码传递给类方法时,通常是如何格式化参数。通过这种方式(与方括号),而不是传统参数(parens)的常规方式之间有什么区别? –