From bdaad2a22ccf95f1a356c4ff048ee9e9b39ebbc6 Mon Sep 17 00:00:00 2001 From: Kir Shatrov Date: Mon, 16 Jun 2014 12:41:46 +0300 Subject: [PATCH] Safe fetch with fallback (fixed #5) --- README.md | 20 ++++++++++++++++++++ lib/russian_central_bank.rb | 10 ++++++++++ 2 files changed, 30 insertions(+) diff --git a/README.md b/README.md index 770de73..260d537 100644 --- a/README.md +++ b/README.md @@ -47,6 +47,26 @@ Or install it yourself as: # Check expiration date bank.rates_expired_at +### Safe rates fetch + +There are some cases, when the `cbr.ru` returns HTTP 302. +To avoid issues in production, you use fallback: + +```ruby +bank = Money::Bank::RussianCentralBank.new +begin + bank.update_rates +rescue Money::Bank::RussianCentralBank::FetchError => e + Rails.logger.info "CBR failed: #{e.response}" + + ## fallback + Money.default_bank = Money::Bank::VariableExchange.new + + Money.default_bank.add_rate(:usd, :eur, 1.3) + Money.default_bank.add_rate(:eur, :usd, 0.7) +end +``` + ## Contributing 1. Fork it diff --git a/lib/russian_central_bank.rb b/lib/russian_central_bank.rb index ddc3ae0..8175a1a 100644 --- a/lib/russian_central_bank.rb +++ b/lib/russian_central_bank.rb @@ -4,6 +4,14 @@ class Money module Bank class RussianCentralBank < Money::Bank::VariableExchange + class FetchError < StandardError + attr_reader :response + + def initialize(message, response=nil) + super(message) + @response = response + end + end CBR_SERVICE_URL = 'http://www.cbr.ru/DailyInfoWebServ/DailyInfo.asmx?WSDL' @@ -65,6 +73,8 @@ def exchange_rates(date) client = Savon::Client.new(wsdl: CBR_SERVICE_URL, log: false, log_level: :error) response = client.call(:get_curs_on_date, message: { 'On_date' => date.strftime('%Y-%m-%dT%H:%M:%S') }) response.body[:get_curs_on_date_response][:get_curs_on_date_result][:diffgram][:valute_data][:valute_curs_on_date] + rescue Wasabi::Resolver::HTTPError => e + raise FetchError.new(e.message, e.response) end def update_parsed_rates rates