Search code examples
ruby-on-railsclasshashclass-method

Call class method with symbol input


I have a class method:

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

I have a rake task that creates a City, with a country_code like "AF". I would like it to replace "AF" with "Afghanistan" by calling the class method and referencing the key-value pair.

The current functionality which sets the country_code to be like "AF" is:

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

I can manually retrieve "Afghanistan" by calling puts CountryCodes.country_codes[:AF]. By combining these tactics, I (incorrectly) thought I could:

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

The failure that occurs when I run this is:

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

How can I correctly call the CountryCodes.country_code class method with a dynamic input of row[:country_code]?


Solution

  • Since CountryCodes.country_code has a hash of symbols, you need to call a symbol when referencing it. For example: country_code["AF"] is NOT the same as country_code[:AF].

    To correct this, convert your string row[:country_code] to a symbol using Ruby's to_sym:

    city = City.create do |c|
       c.name = row[:name] 
       c.country_code = CountryCodes.country_code[row[:country_code].to_sym]  # < .to_sym
    end
    

    Since I cannot see your schema, my answer is also assuming that country_code is a String in your City model (not an integer.)