Cole Bittel
Cole Bittel

Reputation: 2884

Using hash object in lib/assets within a rake task

In my lib/assets/country_codes.rb file:

# lib/assets/country_codes.rb

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

In a rake task, I use:

# 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

I would like to add c.country_code s.t. it is like "Afghanistan". However it is currently added, as in the code above, like "AF".

I would like to implement a lookup against the flat file, so that "AF" is replaced with "Afghanistan".

My current problem is just that I'm having trouble just referencing the hash object. When I try to access

puts "#{CountryCodes.country_codes.AF}"

I am returned with:

undefined method `country_codes' for CountryCodes:Class

How can I access the hash object within the lib/assets/country_codes.rb file?

Upvotes: 4

Views: 209

Answers (1)

Brad Werth
Brad Werth

Reputation: 17647

Change it to a class method, like:

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

You will need to refer to it like:

puts CountryCodes.country_codes[:AF]

Upvotes: 3

Related Questions