ruby-on-railsrubycountries

Rails 5 - Countries gem - flags


I'm trying to figure out how to use the countries gem in my Rails 5 app so that I can display a flag emoji in my view.

In my gemfile, I have:

gem 'countries', :require => 'countries/global'
gem 'country_select'

I have a model called address. It has an attribute called :country

In my address.rb I am trying to copy the gem instructions. The instructions for using the flags say:

Country Code in Emoji

c = Country['MY']
Country.emoji_flag # => "🇺🇸"

The instructions don't make any sense to me. What is "c"? Why isn't "c" used in the 2nd line? Why is "Country" a class name when in the examples above, it's an attribute? Do I need to do something to convert my country attribute in my address table into something that the gem can read to determine which flag to present?

None of these questions appear to be answered anywhere. I think this is another instance of things that are assumed that everyone (except for me) seems to intuitively understand. They are roadblocks for me.

In my address model, I have:

  def country_name
    country = self.country
    ISO3166::Country[country]
  end

  def country_emoji
    country.emoji_flag
  end

The first method works fine. It displays the right country name.

The second method is my attempt at being able to get a flag. In my address view, I then have:

    <%=  Address.first.country_emoji %>

This doesnt work. It produces an error that says:

undefined method `emoji_flag' for "AU":String

AU is the correct code for the relevant country - so it must be working to figure out which country it should be looking for.

If I try changing the second method (so as to use the first method) to:

def country_emoji
    country_name.emoji_flag
  end

I get an error that says:

undefined method `emoji_flag' for #<ISO3166::Country:0x007fe87145d7e0>

Can anyone figure out how to use the countries gem to display a flag?

I saw this post which suggests there is an example app somewhere to show how to apply the instructions in the readme - although that doesnt seem to exist anymore.


Solution

  • To use the flags, I need to update the gem to version 2.5 and the country-select gem needs to be at least v3