Skip to content

Instantly share code, notes, and snippets.

@ifosch
Last active December 4, 2015 17:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ifosch/f3977bcee2b39c90f292 to your computer and use it in GitHub Desktop.
Save ifosch/f3977bcee2b39c90f292 to your computer and use it in GitHub Desktop.
Hackathon #39 - External sources
source 'https://rubygems.org'
gem 'hashie', '~> 3.3.1'
gem 'httparty', '0.11.0'
gem 'restcountry'
#!/usr/bin/env ruby
require 'httparty'
require 'json'
require 'hashie'
require 'restcountry'
require 'pry'
class WorldBankService
def country(iso2)
response = HTTParty.get("http://api.worldbank.org/countries/#{iso2}?format=json")
Hashie::Mash.new(response[1][0])
end
def population(iso2)
indicator(iso2, 'SP.POP.TOTL')
end
def gdp(iso2)
indicator(iso2, 'NY.GDP.MKTP.CD')
end
def indicator(iso2, indicator_name)
response = HTTParty.get("http://api.worldbank.org/countries/#{iso2}/indicators/#{indicator_name}?format=json&frequency=Y")
response[1].map { |entry| Hashie::Mash.new(entry) }
end
end
class Country
attr_reader :name, :capital, :region, :currencies, :languages, :area
def initialize(name)
@rest_country = Restcountry::Country.find_by_name(name.downcase)
wb_service = WorldBankService.new
@world_bank_country = wb_service.country(@rest_country.alpha2Code)
@name = @world_bank_country.name
@capital = @world_bank_country.capital
@region = @rest_country.region
@currencies = @rest_country.currencies
@languages = @rest_country.languages
@area = @rest_country.area
@population = wb_service.population(name.downcase)
@gdp = wb_service.gdp(name.downcase)
end
def gdp
@gdp.reduce({}) do |yearly_gdp, gross_domestic_product|
yearly_gdp[gross_domestic_product.date] = gross_domestic_product.value
yearly_gdp
end.sort.to_h
end
def population
@population.reduce({}) do |yearly_pop, pop|
yearly_pop[pop.date] = pop.value
yearly_pop
end.sort.to_h
end
def to_json
{
name: name,
capital: capital,
region: region,
currencies: currencies,
languages: languages,
area: area,
population: population,
gdp: gdp
}.to_json
end
end
c = Country.new(ARGV.first)
puts "#{c.name}, country in #{c.region}, which capital is #{c.capital}."
puts "With an area of #{c.area}"
puts 'Population for the last 5 years:'
c.population.sort.reverse[0..5].to_h.each do |year, pop|
puts " #{year}: #{pop}"
end
puts 'GDP for the last 5 years:'
c.gdp.sort.reverse[0..5].to_h.each do |year, gdp|
puts " #{year}: #{gdp}"
end
puts ""
puts c.to_json
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment