How to list all continents with the countries gem?

412 Views Asked by At

Using the Countries gem https://github.com/hexorx/countries

We have the method:

ISO3166::Country.find_all_countries_by_continent('Europe')

We also have: ISO3166::Country.countries

But we don't have: ISO3166::Country.continents

I want to have a 'Filter by continent' select which could be translated using I18n.

Is there an easy way to get all available continents?

2

There are 2 best solutions below

0
Mahefa On

As I know (I can be wrong), I think hexorx/countries not give you this possibility natively.

Ps : I have created an feature request for this if it can make things happen.

0
engineersmnky On

You can get all the continents using

ISO3166::Data.cache.map {|_,v| v['continent']}.uniq
#=> ["Asia", "North America", "Africa", "Europe", "South America", "Antarctica", "Australia"]

Due to the fact that this list is highly unlikely to change in the foreseeable future you can just cache these results for your self

ISO3166::CONTINENTS = ISO3166::Data.cache.map {|_,v| v['continent']}.uniq.sort

Then you can just reuse the constant ISO3166::CONTINENTS anywhere you need to.

That being said the i18n_data gem (that is used for translation of countries) does not appear to provide translation for continent names so that would likely fall on your shoulders to maintain.

A Set might make this slightly more efficient too: (although since getting the continents is simply Array traversal and Hash lookup it is already reasonably fast)

ISO3166::CONTINENTS = ISO3166::Data.cache.each_with_object(Set.new)  do |(_,v),s| 
  s.add(v['continent'])
end.sort