Rails 5 - Countries gem - flags

若如初见. 提交于 2020-01-03 04:49:07

问题


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.


回答1:


As it states in gem docs, in order to use syntax like

c = Country['US']

you should at first add this to Gemfile:

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

Test in console:

irb(main):001:0> require "countries/global"
=> true
irb(main):002:0> country = Country.new('US')
=> #<Country:0x000000050dc4d8 @country_data_or_code="US" ... >
irb(main):003:0> country.emoji_flag
=> "🇺🇸"

(I really don't know why the same docs suggests syntax Country.emoji_flag).




回答2:


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



来源:https://stackoverflow.com/questions/41082840/rails-5-countries-gem-flags

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!