class C::Rates

Attributes

coins[RW]
count[R]
currency[RW]
data[R]
prices[R]
response[R]
table[R]
url[R]

Public Class Methods

get!( currency = :eur, opts = {} ) click to toggle source
# File lib/crates.rb, line 20
def self.get!( currency = :eur, opts = {} )
  @rates = Rates.new currency, opts
  @rates.get
end
new( currency = :eur, opts = {} ) click to toggle source
# File lib/crates.rb, line 25
def initialize( currency = :eur, opts = {} )
  @save  = opts[:save ].nil? ? true : opts[:save]
  @print = opts[:print].nil? ? true : opts[:print]
  @coins = opts[:coins].nil? ? COINS : Array(opts[:coins])
  @currency = currency.to_s.upcase
end

Public Instance Methods

get( currency = nil, opts = {} ) click to toggle source
# File lib/crates.rb, line 32
def get( currency = nil, opts = {} )
  @save  = opts[:save]  unless opts[:save].nil?
  @print = opts[:print] unless opts[:print].nil?
  opts[:coins] ||= @coins
  currency     ||= @currency
  @table = currency.to_s.downcase  + '_rates.csv'
  @count = 0
  execute_request(opts[:coins], currency)
end
price( coin ) click to toggle source
# File lib/crates.rb, line 42
def price( coin )
  @prices[coin.to_s.upcase]
end
print?() click to toggle source
save?() click to toggle source
# File lib/crates.rb, line 46
def save?
  @save == true
end

Private Instance Methods

create_csv_headers( coins = [] ) click to toggle source
# File lib/crates.rb, line 95
def create_csv_headers( coins = [] )
  header_array = ['TIME']
  coins.each { |coin| header_array << coin }
  CSV.open(@table, "w" ) { |header| header << header_array }
end
execute_request( coins = @coins, currency = @currency ) click to toggle source
# File lib/crates.rb, line 56
def execute_request( coins = @coins, currency = @currency )
  @prices, @data_array, coin_uri = {}, [], ''
  coins.collect { |coin| coin_uri << "fsyms=#{coin}&" }
  @url = URL + "#{coin_uri}tsyms=#{currency}"
  @response = RestClient.get @url
  @data = JSON.parse @response
  @data_array << Time.now.to_s
  coins.each do |coin|
    @data_array << value = @data["RAW"][coin.to_s.upcase][currency.to_s.upcase]["PRICE"].round(2)
    @prices[coin] = value
  end
  print_data_for(currency) if print?
  save_data(coins) if save?
 rescue
  @count += 1
  if @count >= MAX_RETRY
    puts @response.to_s.split(',')
    exit 1
  else
    execute_request(coins, currency)
  end
end
print_data_for( currency ) click to toggle source
save_data( coins = nil ) click to toggle source
# File lib/crates.rb, line 89
def save_data( coins = nil )
  coins ||= @coins
  create_csv_headers(coins) unless File.exist?(@table)
  CSV.open(@table, 'ab') { |column| column << @data_array }
end