From ad64574745f8fbaa75b0c5a475b665a4b39a7b3b Mon Sep 17 00:00:00 2001 From: Vincent Durand Date: Thu, 22 Sep 2016 18:53:31 +0200 Subject: [PATCH] Add GET #converter API route It adds a quote helper which return the Quote instance to be injected, and uses this new object for the quote's attributes. --- lib/api.rb | 30 +++++++++++++++++++++++------- spec/api_spec.rb | 5 +++++ 2 files changed, 28 insertions(+), 7 deletions(-) diff --git a/lib/api.rb b/lib/api.rb index aa7c232..7e5b7ba 100644 --- a/lib/api.rb +++ b/lib/api.rb @@ -4,6 +4,7 @@ require 'oj' require 'sinatra' require 'rack/cors' require 'quote' +require 'converter' configure :development do set :show_exceptions, :after_handler @@ -22,11 +23,17 @@ end helpers do def quote - @quote ||= Quote.new(params).attributes.tap do |data| + @quote ||= Quote.new(params) + end + + def quote_attributes + @quote_attributes ||= quote.attributes.tap do |data| data[:rates].keep_if { |k, _| symbols.include?(k) } if symbols end - rescue Quote::Invalid => ex - halt 422, encode_json(error: ex.message) + end + + def converter + @converter ||= Converter.new(params) end def symbols @@ -67,15 +74,24 @@ get '/' do end get '/latest' do - last_modified quote[:date] - jsonp quote + last_modified quote_attributes[:date] + jsonp quote_attributes end get(/(?\d{4}-\d{2}-\d{2})/) do - last_modified quote[:date] - jsonp quote + last_modified quote_attributes[:date] + jsonp quote_attributes +end + +get '/converter' do + params[:base] = params[:from] + jsonp Hash(amount: converter.convert(quote)) end not_found do halt 404, encode_json(error: 'Not found') end + +error Quote::Invalid do |ex| + halt 422, encode_json(error: ex.message) +end diff --git a/spec/api_spec.rb b/spec/api_spec.rb index c79b7df..ee86446 100644 --- a/spec/api_spec.rb +++ b/spec/api_spec.rb @@ -66,4 +66,9 @@ describe 'the API' do assert headers.key?('Access-Control-Allow-Methods') end end + + it 'returns converted amount' do + get '/converter?to=USD&amount=100' + json['amount'].wont_be :nil? + end end