• Stars
    star
    67
  • Rank 446,797 (Top 10 %)
  • Language
    Ruby
  • Created about 11 years ago
  • Updated about 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Convert country names and codes to a standard.

NormalizeCountry¶ ↑

Convert country names and codes to a standard.

<img src=“https://travis-ci.org/sshaw/normalize_country.svg?branch=master” alt=“Build Status” /> <img src=“https://codeclimate.com/github/sshaw/normalize_country.svg” />

Overview¶ ↑

require "normalize_country"

NormalizeCountry("America")                       # "United States"
NormalizeCountry("United States of America")      # "United States"
NormalizeCountry("USA",  :to => :official)        # "United States of America"
NormalizeCountry("Iran", :to => :official)        # "Islamic Republic of Iran"
NormalizeCountry("U.S.", :to => :alpha2)          # "US"
NormalizeCountry("U.S.", :to => :numeric)         # "840"
NormalizeCountry("US",   :to => :fifa)            # "USA"
NormalizeCountry("US",   :to => :emoji)           # "🇺🇸"
NormalizeCountry("US",   :to => :shortcode)       # ":flag-us:"
NormalizeCountry("Iran", :to => :alpha3)          # "IRN"
NormalizeCountry("Iran", :to => :ioc)             # "IRI"
NormalizeCountry("DPRK", :to => :short)           # "North Korea"
NormalizeCountry("North Korea", :to => :iso_name) # "Korea, Democratic People's Republic Of"

# Or
NormalizeCountry.convert("U.S.", :to => :alpha2)  # "US"

# Set the default
NormalizeCountry.to = :alpha3
NormalizeCountry.convert("Mexico")                 # "MEX"
NormalizeCountry.convert("United Mexican States")  # "MEX"

Installation¶ ↑

Rubygems (part of Ruby):

gem install normalize_country

Bundler:

gem "normalize_country"

Supported Conversions¶ ↑

In addition to trying to convert from common, non-standardized names and abbrivations, NormalizeCountry will convert to/from the following:

:alpha2

ISO 3166-1 alpha-2

:alpha3

ISO 3166-1 alpha-3

:emoji

The country’s emoji

:fifa

FIFA (International Federation of Association Football)

:ioc

International Olympic Committee

:iso_name

Country name used by ISO 3166-1

:numeric

ISO 3166-1 numeric code

:official

The country’s official name

:short

A shortned version of the country’s name, commonly used when speaking and/or writing (US English)

:shortcode:

Emoji shortcode

A list of valid formats can be obtained by calling NormalizeCountry.formats.

Obtaining an Array or Hash¶ ↑

NormalizeCountry.to_a                              # Defaults to NormalizeCountry.to
NormalizeCountry.to_a(:ioc)                        # Array of IOC codes in ascending order
NormalizeCountry.to_h(:ioc)                        # :ioc => NormalizeCountry.to
NormalizeCountry.to_h(:ioc, :to => :numeric)       # :ioc => :numeric

Conversion Utility¶ ↑

A small script is included that can convert country names contained in a DB table or a set of XML or CSV files

shell > normalize_country -h
usage: normalize_country [options] SOURCE
    -h, --help                       Show this message
    -f, --format FORMAT              The format of SOURCE
    -t, --to CONVERSION              Convert country names to this format (see docs for valid formats)
    -l, --location LOCATION          The location of the conversion

Some examples

normalize_country -t alpha2 -l 'Country Name' -f csv data.csv
normalize_country -t numeric -l countries.code -f db postgres://usr:pass@localhost/conquests
normalize_country -t fifa -l //teams[@sport = 'fĂştbol americano']//country -f xml data.xml

If the format is xml or csv you can spefify a directory instead of a filename

normalize_country -t alpha2 -l 'Country Name' -f csv /home/sshaw/capital-losses/2008

With a format of csv it will read all files with an extension of csv or tsv. For csv and xml the original file(s) will be overwritten with new file(s) containing the converted country names.

To convert an XML file with namespaces just include the namespace prefix defined in the file in the XPath query (LOCATION).

The db format’s SOURCE argument must be a Sequel connection string. Here LOCATION is in the format table.column, which will be updated with the converted name.

Random Country Data for Your Tests¶ ↑

Random data generating gems like Faker and RandomData don’t generate much country data. If you’d like to use this gem to do so I suggest checking out this gist: gist.github.com/sshaw/6068404

Faulty/Missing/Erroneous Country Names¶ ↑

Please submit a patch or open an issue.

This code was -to some extent- part of a larger project that allowed users to perform a free-text search by country. Country names were stored in the DB by their ISO names.

Several years later at work we had to extract country names from a web service that didn’t standardize them. Sometimes they used UK, other times U.K. It then occured to me that this code could be useful outside of the original project. The web service was fixed but, nevertheless…

Somewhat Similar Gems¶ ↑

Upon further investigation I’ve found the following:

  • Carmen: ISO country names and states/subdivisions

  • countries ISO country names, states/subdivisions, currency, E.164 phone numbers and language translations

  • country_codes ISO country names and currency data

  • i18n_data: ISO country names in different languages, includes alpha codes

  • ModelUN: Similar to this gem but with less support for conversion, it does include US states

See Also¶ ↑

More Repositories

1

git-link

Emacs package to get the GitHub/Bitbucket/GitLab/... URL for a buffer location
Emacs Lisp
380
star
2

copy-as-format

Emacs function to copy buffer locations as GitHub/Slack/JIRA etc... formatted code
Emacs Lisp
133
star
3

itunes_store_transporter

Upload and manage your assets in the iTunes Store using the iTunes Store’s Transporter (iTMSTransporter).
Ruby
117
star
4

export-pull-requests

Export pull requests and/or issues to a CSV file. Supports GitHub, GitLab, and Bitbucket
Ruby
107
star
5

itunes_store_transporter_web

iTunes Store Transporter GUI: GUI and workflow automation for the iTunes Store’s Transporter (iTMSTransporter)
Ruby
80
star
6

yymmdd

Tiny DSL for idiomatic date parsing and formatting in Ruby
Ruby
78
star
7

ddex

DDEX metadata serialization for Ruby
Ruby
51
star
8

build-status

Emacs minor mode that monitors and shows a buffer's build status in the mode line.
Emacs Lisp
27
star
9

class2

Easily create Ruby class hierarchies that support nested attributes, type conversion, serialization, equality, and more.
Ruby
14
star
10

output-as-format

Output stdin as GitHub/Slack/Jira etc... formatted code, lists, or quotes
Perl
12
star
11

jaxb2ruby

Generate pure Ruby objects from an XML schema (XSD) using JAXB and JRuby. Use your favorite XML to object mapper or a custom ERB template.
Ruby
12
star
12

batchlabels

Add or remove labels in batches to/from GitHub issues and pull requests.
Go
8
star
13

angry_raise

raise Ruby exceptions, with emotion and intensity
Ruby
6
star
14

optout

The opposite of getopt(): validate an option hash and turn it into something appropriate for exec() and system()-like functions
Ruby
5
star
15

URI-fasp

URI handler for Aspera's FASP protocol
Perl
5
star
16

transform_legacy_attribute_methods

A Rails plugin that allows you to transform your ActiveRecord model's "legacy" attribute methods into attribute aliases that can be used in dynamic finders and attribute hashes.
Ruby
5
star
17

Time-Timecode

Video timecode class for Perl and command line program. Supports any frame rate, conversions, drop/non-drop frame counts and more.
Perl
5
star
18

issue-link

Get the link to JIRA/Tracker/GitHub issues. Turn bug/feature/issue IDs into links.
Emacs Lisp
4
star
19

ruby-factory-mode

Emacs minor mode for Ruby test object generation libraries
Emacs Lisp
3
star
20

Mojolicious-Plugin-FormFields

Use objects and data structures in your forms
Perl
3
star
21

dotfiles

My dotfiles. Everything but Emacs, which has its own repository: https://github.com/sshaw/emacs.d
Shell
3
star
22

ruby-jing

RELAX NG schema validation in Ruby using the Jing CLI
Ruby
3
star
23

xslt-timecode

A pure, dependency free, XSLT 1.0 library for video timecode manipulation
XSLT
2
star
24

glc

The GitHub Link Checker. Monitor GitHub activity for links that aren't permanent, and do something.
Go
2
star
25

interrobang

Did the method end with "?" or "!"‽ Interrobang gives you the best of both worlds‽
Ruby
2
star
26

selfie_formatter

The RSpec Selfie Formatter: A Formatter that takes photos of you while your tests run and uses them to track progress and format the results.
Ruby
2
star
27

jquery-selectunique

Given a group of select fields with the same options, SelectUnique will remove an option from the other select fields when it's selected, and put it back when it's changed.
JavaScript
2
star
28

markdown_usage

Output a colorized version of your program's usage using a Markdown document embedded in your script, from your project's README, or anywhere else.
Ruby
1
star
29

Mojolicious-Plugin-ParamExpand

Turns request parameters into nested data structures using CGI::Expand.
Perl
1
star
30

logging-honeybadger

Honeybadger appender for the Logging gem
Ruby
1
star
31

logging-appenders-airbrake

Airbrake appender for the Logging gem
Ruby
1
star
32

page_number

Page number validation. Utility methods for pagination page and per page that make sure you'll always have a valid number
Ruby
1
star
33

require3

Kernel#require something and make it accessible via a different namespace.
Ruby
1
star
34

alias2

Make classes, modules, and constants accessible via a different namespace.
Ruby
1
star
35

emacs.d

My Emacs config
Emacs Lisp
1
star
36

select-unique

Given a group of HTML select elements with the same options, Select Unique will remove an option from the other select elements when it's selected, and put it back when it's changed.
JavaScript
1
star
37

Mojolicious-Command-secret

Generate a secret() using random bytes and add it to your app
Perl
1
star
38

keep_defaults

Prevent ActiveRecord attributes for not null columns with default values from being set to nil.
Ruby
1
star
39

Mojolicious-Plugin-DigestAuth

HTTP Digest Authentication for Mojolicious
Perl
1
star