Skip to content

Instantly share code, notes, and snippets.

@waclock
Created July 25, 2019 20:59
Show Gist options
  • Save waclock/b33c97ff1632358667123c4af2968691 to your computer and use it in GitHub Desktop.
Save waclock/b33c97ff1632358667123c4af2968691 to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
require 'date'
require 'nokogiri'
require 'net/http'
require 'ostruct'
require 'awesome_print'
require 'json'
class CurrencyService
CENTRAL_BANK_URL = 'https://si3.bcentral.cl/bdemovil/BDE/IndicadoresDiarios?fecha='
API_ENDPOINT = 'http://apilayer.net/api/historical?currencies=CLP&date='
API_KEY = '3b2c596b9e0c3b60ca33663ed9350614'
attr_accessor :last_response, :response, :fetch_method
def values(from_date, to_date)
output = {}
self.last_response = nil
(from_date..to_date).each do |date|
self.response = fetch_central_bank(date)
output[date.strftime('%Y-%m-%d')] = { uf: parse_currency('uf'), usd: parse_currency('usd') }
self.last_response = response
end
output
end
def parse_currency(currency_type)
{ today: response.send(currency_type), diff: (!last_response.nil? ? last_response.send(currency_type) - response.send(currency_type) : nil) }
end
def fetch_from_api(date)
parsed_date = date.strftime('%Y-%m-%d')
date_uri = URI("#{API_ENDPOINT}#{parsed_date}&access_key=#{API_KEY}")
json = JSON.parse(Net::HTTP.get_response(date_uri).body)
ap json
OpenStruct.new(uf: 0, usd: json['quotes']['USDCLP'], date: date.strftime('%Y-%m-%d'))
end
def fetch_central_bank(date)
parsed_date = date.strftime('%d-%m-%Y')
date_uri = URI("#{CENTRAL_BANK_URL}#{parsed_date}")
html_doc = Nokogiri::HTML(Net::HTTP.get_response(date_uri).body)
uf = cleanse_currency_value(html_doc.css('table.tableUnits td')[1].content)
usd = cleanse_currency_value(html_doc.css('table.tableUnits')[1].css('td')[1].content)
OpenStruct.new(uf: uf, usd: usd, date: date.strftime('%Y-%m-%d'))
end
def cleanse_currency_value(value)
value.to_s.gsub('.', '').gsub(',', '.').to_f
end
end
currency_service = CurrencyService.new
ap currency_service.values(Date.new(2019, 1, 31), Date.new(2019, 2, 1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment