elikem
6/3/2014 - 7:06 AM

Sinatra Demo App -- Bitcoin Prices

Sinatra Demo App -- Bitcoin Prices

require "sinatra"

require 'mechanize'
require 'json'
require 'hashie'
require 'bigdecimal'

require "sqlite3"
require "active_record"

ActiveRecord::Base.establish_connection(
    adapter: 'sqlite3',
    database: 'database.db')

API_URL = 'http://www.cryptocoincharts.info/v2/api'

ActiveRecord::Schema.define do
  unless ActiveRecord::Base.connection.tables.include? 'pricings'
    create_table :pricings do |t|
      t.column :coin,     :string
      t.column :price,    :decimal
      t.column :price_before_24h, :decimal
      t.column :volume_first, :decimal
      t.column :volume_second, :decimal
      t.column :volume_btc, :decimal
      t.column :best_market, :string
    end
  end
end

class Pricings < ActiveRecord::Base

end

get "/" do
  response = JSON.parse(Mechanize.new.post(
                          "#{API_URL}/tradingPairs", 
                          {:pairs => "btc_usd,doge_usd,drk_usd" }).body
                        )
  last_responses = []
  response.each {|pricing| last_responses << Pricings.create({coin: pricing["id"],
                                              price: pricing["price"],
                                              price_before_24h: pricing["price_before_24h"],
                                              volume_first: pricing["volume_first"],
                                              volume_second: pricing["volume_second"],
                                              volume_btc: pricing["volume_btc"],
                                              best_market: pricing["best_market"]}
                                              )}
  
  html = '<!doctype html>
          <head>
            <meta http-equiv="refresh" content="60">
          </head>
          <body>
          '
  last_responses
  .each do |pricing|
    html += "<div id=#{pricing.id}>#{pricing.id}. #{pricing.coin} -- #{pricing.price}</div>"
  end
  html += "</body>"
  html
end