Sha256: 82c79c013f5083605b731d10776f31a185b574ba25f47d5830c6ce16ea7e7381

Contents?: true

Size: 1.71 KB

Versions: 2

Compression:

Stored size: 1.71 KB

Contents

require 'concurrency/configuration'
require "concurrency/version"
require 'net/http'
require 'json'

module Concurrency
    class << self
        attr_accessor :configuration
    end    
    
    def self.configuration
        @configuration ||= Configuration.new
    end

    def self.reset
        @configuration = Configuration.new
    end

    def self.configure
        yield(configuration)
    end
    
    def self.convert(*args)
        if args.length == 3
            Concurrency.convert_full(*args)
        elsif args.length == 2
            Concurrency.convert_full(args[0], Concurrency.configuration.from_currency, args[1])
        else
            Concurrency.convert_full(args[0], Concurrency.configuration.from_currency, Concurrency.configuration.to_currency)
        end
    end
    
    def self.conversion_rate(from = Concurrency.configuration.from_currency, to = Concurrency.configuration.to_currency)
        if from == to
            return 1.0
        else
            rate = Concurrency.get_rate(from, to)
            return rate
        end
    end
    
    private
  
    def self.convert_full(initial, from, to)
        if from == to
            return initial
        end
        rate = Concurrency.get_rate(from, to)
        if rate == nil
            return nil
        else
            return initial*rate
        end
    end
    
    def self.get_rate(from, to)
        url = "http://api.fixer.io/latest?base=#{from}&symbols=#{to}"
        uri = URI(url)
        response = Net::HTTP.get(uri)
        if response == nil
            return nil
        else
            parsed_response = JSON.parse(response)
            rate = (parsed_response["rates"]["#{to}"]).to_f
            return rate
        end
    end
    
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
concurrency-0.1.1 lib/concurrency.rb
concurrency-0.1.0 lib/concurrency.rb