Skip to content

Instantly share code, notes, and snippets.

@sergeych
Created May 12, 2017 00:17
Show Gist options
  • Save sergeych/c19179b81cb752db14bfd50633f9a902 to your computer and use it in GitHub Desktop.
Save sergeych/c19179b81cb752db14bfd50633f9a902 to your computer and use it in GitHub Desktop.
Получение курса одной валюты на заданную дату от сервиса ЦБ РФ
# this code is provided under MIT license terms
# [email protected]
require 'savon'
#
# Интерфейс к сервису по РФ: курс одной валюты на заданную дату
# возвращает #rate как строку, как число можно получить float_rate,
# decimal_rate.
#
# используется сервис: http://www.cbr.ru/DailyInfoWebServ/DailyInfo.asmx?WSDL
#
# @author [email protected]
class CBRRate
# @return [String] currency full name as returned by the bank's service
attr :name,
# @return [Date] as passed to the constructor
:date,
# @return [String] exchange rate as String
:rate,
# @return [String] Currency symbolic code, e.g. USD
:code
# Creates an instance ot currency rate by loading data from Russia's central bank soap
# service.
#
# @param [Date or Time] date object, time object or anyting that has .strftime() methid
# @param [String] currency_code known to ЦБ РФ (например EUR)
def initialize date, currency_code
# Convert date to something CB interface takes
cbr_date = date.strftime("%Y-%m-%dT07:00:00+03:00")
@@client = Savon.client(wsdl: "http://www.cbr.ru/DailyInfoWebServ/DailyInfo.asmx?WSDL", log: false)
res = @@client.call(:get_curs_on_date, message: {
'On_date' => cbr_date
})
@raw_data = res.body[:get_curs_on_date_response][:get_curs_on_date_result][:diffgram][:valute_data]
raise ArgumentError, "No rate data returned for #{date}" if @raw_data == nil
data = @raw_data[:valute_curs_on_date].find{|x| x[:vch_code] == currency_code }
@rate = data[:vcurs]
@name = data[:vname].strip
@code = currency_code
end
# rate as float. not recommended. use {#decimal_rate} instead.
def float_rate
@float_rate ||= @rate.to_f
end
# exhnage rate as a BigDecimal. recommended to use in calculations
def decimal_rate
@decimal_rate ||= BigDecimal.new(@rate)
end
def to_s
"#{@name}/Рубль:#{@rate}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment