Skip to content

Commit

Permalink
Fix RuboCop offenses
Browse files Browse the repository at this point in the history
  • Loading branch information
sferik committed Dec 31, 2013
1 parent 58985fc commit 6ca22fd
Show file tree
Hide file tree
Showing 23 changed files with 278 additions and 299 deletions.
12 changes: 6 additions & 6 deletions lib/faraday/response/raise_mtgox_error.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@

module Faraday
class Response::RaiseMtGoxError < Response::Middleware
def on_complete(env)
def on_complete(env) # rubocop:disable CyclomaticComplexity
if 200 == env[:status] && 'MySQL error, please retry later' == env[:body]
raise MtGox::MysqlError, "MySQL error, please retry later"
elsif 403 == env[:status] && JSON.load(env[:body])["result"] == "error"
raise MtGox::UnauthorizedError, JSON.load(env[:body])["error"]
elsif 404 != env[:status] && JSON.load(env[:body])["result"] == "error"
raise MtGox::Error, JSON.load(env[:body])["error"]
fail(MtGox::MysqlError, env[:body])
elsif 403 == env[:status] && JSON.load(env[:body])['result'] == 'error'
fail(MtGox::UnauthorizedError, JSON.load(env[:body])['error'])
elsif 404 != env[:status] && JSON.load(env[:body])['result'] == 'error'
fail(MtGox::Error, JSON.load(env[:body])['error'])
end
end
end
Expand Down
2 changes: 1 addition & 1 deletion lib/mtgox.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ def method_missing(method, *args, &block)
new.send(method, *args, &block)
end

def respond_to?(method, include_private=false)
def respond_to?(method, include_private = false)
new.respond_to?(method, include_private) || super(method, include_private)
end
end
Expand Down
3 changes: 1 addition & 2 deletions lib/mtgox/ask.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,7 @@ def initialize(client, hash = nil)
end

def eprice
price / (1 - self.client.commission)
price / (1 - client.commission)
end

end
end
2 changes: 1 addition & 1 deletion lib/mtgox/balance.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ module MtGox
class Balance
attr_accessor :currency, :amount

def initialize(currency=nil, amount=nil)
def initialize(currency = nil, amount = nil)
self.currency = currency.to_s.upcase
self.amount = BigDecimal(amount.to_s)
end
Expand Down
3 changes: 1 addition & 2 deletions lib/mtgox/bid.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,7 @@ def initialize(client, hash = nil)
end

def eprice
price * (1 - self.client.commission)
price * (1 - client.commission)
end

end
end
78 changes: 32 additions & 46 deletions lib/mtgox/client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,13 @@
require 'mtgox/order_result'

module MtGox
class Client
class Client # rubocop:disable ClassLength
include MtGox::Connection
include MtGox::Request
include MtGox::Value
include MtGox::Configuration

ORDER_TYPES = {sell: "ask", buy: "bid"}
ORDER_TYPES = {:sell => 'ask', :buy => 'bid'}

def initialize
reset
Expand Down Expand Up @@ -76,8 +76,8 @@ def lag
lag = get('/api/1/generic/order/lag')
Lag.new(lag['lag'], lag['lag_secs'], lag['lag_text'], lag['length'])
end
alias order_lag lag
alias orderlag lag
alias_method :order_lag, :lag
alias_method :orderlag, :lag

# Fetch both bids and asks in one call, for network efficiency
#
Expand All @@ -87,17 +87,9 @@ def lag
# MtGox.offers
def offers
offers = get('/api/1/BTCUSD/depth/fetch')
asks = offers['asks'].sort_by do |ask|
ask['price_int'].to_i
end.map! do |ask|
Ask.new(self, ask)
end
bids = offers['bids'].sort_by do |bid|
-bid['price_int'].to_i
end.map! do |bid|
Bid.new(self, bid)
end
{asks: asks, bids: bids}
asks = offers['asks'].sort_by { |ask| ask['price_int'].to_i }.map { |ask| Ask.new(self, ask) }
bids = offers['bids'].sort_by { |bid| -bid['price_int'].to_i }.map { |bid| Bid.new(self, bid) }
{:asks => asks, :bids => bids}
end

# Fetch open asks
Expand Down Expand Up @@ -147,9 +139,9 @@ def max_bid
# @example
# MtGox.trades
# MtGox.trades :since => 12341234
def trades(opts={})
def trades(opts = {})
get('/api/1/BTCUSD/trades/fetch', opts).
sort_by{|trade| trade['date']}.map do |trade|
sort_by { |trade| trade['date'] }.map do |trade|
Trade.new(trade)
end
end
Expand All @@ -161,7 +153,7 @@ def trades(opts={})
# @example
# MtGox.rights
def rights
post("/api/1/generic/info")["Rights"]
post('/api/1/generic/info')['Rights']
end

# Fetch your current balance
Expand Down Expand Up @@ -241,14 +233,12 @@ def sell!(amount, price)
# # Sell one bitcoin for $123
# MtGox.add_order! :sell, 1.0, 123.0
def order!(type, amount, price)
order = {type: order_type(type), amount_int: intify(amount,:btc)}
if price != :market
order[:price_int] = intify(price, :usd)
end
order = {:type => order_type(type), :amount_int => intify(amount, :btc)}
order[:price_int] = intify(price, :usd) if price != :market
post('/api/1/BTCUSD/order/add', order)
end
alias add_order! order!
alias addorder! order!
alias_method :add_order!, :order!
alias_method :addorder!, :order!

# Cancel an open order
#
Expand All @@ -268,22 +258,19 @@ def order!(type, amount, price)
# MtGox.cancel my_order
# MtGox.cancel {'oid' => '1234567890'}
def cancel(args)
if args.is_a?(Hash)
args = args['oid']
end

args = args['oid'] if args.is_a?(Hash)
orders = post('/api/1/generic/orders')
order = orders.find{|order| order['oid'] == args.to_s}
order = orders.detect { |o| o['oid'] == args.to_s }
if order
res = post('/api/1/BTCUSD/order/cancel', oid: order['oid'])
orders.delete_if{|o| o['oid'] == res['oid']}
res = post('/api/1/BTCUSD/order/cancel', :oid => order['oid'])
orders.delete_if { |o| o['oid'] == res['oid'] }
parse_orders(orders)
else
raise MtGox::OrderNotFoundError
fail MtGox::OrderNotFoundError
end
end
alias cancel_order cancel
alias cancelorder cancel
alias_method :cancel_order, :cancel
alias_method :cancelorder, :cancel

# Transfer bitcoins from your Mt. Gox account into another account
#
Expand All @@ -296,10 +283,10 @@ def cancel(args)
# MtGox.withdraw! 1.0, '1KxSo9bGBfPVFEtWNLpnUK1bfLNNT4q31L'
def withdraw!(amount, address)
if amount >= 1000
raise FilthyRichError,
"#withdraw! take bitcoin amount as parameter (you are trying to withdraw #{amount} BTC"
fail FilthyRichError,
"#withdraw! take bitcoin amount as parameter (you are trying to withdraw #{amount} BTC"
else
post('/api/1/generic/bitcoin/send_simple', {amount_int: intify(amount, :btc), address: address})['trx']
post('/api/1/generic/bitcoin/send_simple', :amount_int => intify(amount, :btc), :address => address)['trx']
end
end

Expand All @@ -311,7 +298,7 @@ def withdraw!(amount, address)
# trade_id, page
# @see https://en.bitcoin.it/wiki/MtGox/API/HTTP/v1#Your_wallet_history
def history(currency, params = {})
post('/api/1/generic/wallet/history', params.merge(currency: currency))
post('/api/1/generic/wallet/history', params.merge(:currency => currency))
end

# Fetch information about a particular transaction
Expand All @@ -321,15 +308,15 @@ def history(currency, params = {})
# @param order_id [String] the order id
# @return [OrderResult]
def order_result(offer_type, order_id)
OrderResult.new(post('/api/1/generic/order/result', {type: offer_type, order: order_id}))
OrderResult.new(post('/api/1/generic/order/result', :type => offer_type, :order => order_id))
end

private

def parse_balance(info)
balances = []
info['Wallets'].each do |currency, wallet|
value = currency == "BTC" ? value_bitcoin(wallet['Balance']) : value_currency(wallet['Balance'])
value = currency == 'BTC' ? value_bitcoin(wallet['Balance']) : value_currency(wallet['Balance'])
balances << Balance.new(currency, value)
end
balances
Expand All @@ -338,24 +325,23 @@ def parse_balance(info)
def parse_orders(orders)
buys = []
sells = []
orders.sort_by{|order| order['date']}.each do |order|
orders.sort_by { |order| order['date'] }.each do |order|
case order['type']
when ORDER_TYPES[:sell]
sells << Sell.new(order)
when ORDER_TYPES[:buy]
buys << Buy.new(order)
end
end
{buys: buys, sells: sells}
{:buys => buys, :sells => sells}
end

def order_type(type)
unless ["bid", "ask"].include?(type.to_s)
ORDER_TYPES[type.downcase.to_sym]
else
if %w[bid ask].include?(type.to_s)
type
else
ORDER_TYPES[type.downcase.to_sym]
end
end

end
end
2 changes: 1 addition & 1 deletion lib/mtgox/configuration.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ module Configuration
DEFAULT_COMMISSION = BigDecimal('0.0065').freeze
DEFAULT_NONCE_TYPE = :nonce

attr_accessor *VALID_OPTIONS_KEYS
attr_accessor(*VALID_OPTIONS_KEYS)

# When this module is extended, set all configuration options to their default values
def self.extended(base)
Expand Down
8 changes: 4 additions & 4 deletions lib/mtgox/connection.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@ module Connection

def connection
options = {
headers: {
accept: 'application/json',
user_agent: "mtgox gem #{MtGox::Version}",
:headers => {
:accept => 'application/json',
:user_agent => "mtgox gem #{MtGox::Version}",
},
url: 'https://data.mtgox.com',
:url => 'https://data.mtgox.com',
}

Faraday.new(options) do |connection|
Expand Down
1 change: 0 additions & 1 deletion lib/mtgox/error.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,3 @@ class UnauthorizedError < Error; end
class FilthyRichError < Error; end
class OrderNotFoundError < Error; end
end

2 changes: 1 addition & 1 deletion lib/mtgox/lag.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ module MtGox
class Lag
attr_accessor :microseconds, :seconds, :text, :length

def initialize(lag=nil, lag_secs=nil, lag_text=nil, length=nil)
def initialize(lag = nil, lag_secs = nil, lag_text = nil, length = nil)
self.microseconds = lag.to_i
self.seconds = BigDecimal(lag_secs.to_s)
self.text = lag_text
Expand Down
2 changes: 1 addition & 1 deletion lib/mtgox/order.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ module MtGox
class Order < Offer
attr_accessor :id, :date, :item, :status, :currency

def initialize(order={})
def initialize(order = {})
self.id = order['oid']
self.date = Time.at(order['date'].to_i)
self.amount = BigDecimal(order['amount']['value'])
Expand Down
24 changes: 12 additions & 12 deletions lib/mtgox/order_result.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,42 +7,42 @@ def initialize(json)
end

def id
@json["order_id"]
@json['order_id']
end

def trades
@json["trades"].map{|t| Trade.new(coerce_trade(t)) }
@json['trades'].map { |t| Trade.new(coerce_trade(t)) }
end

def total_spent
to_decimal "total_spent", @json
to_decimal 'total_spent', @json
end

def total_amount
to_decimal "total_amount", @json
to_decimal 'total_amount', @json
end

def avg_cost
to_decimal "avg_cost", @json
to_decimal 'avg_cost', @json
end

private
private

def to_decimal(key, json)
data = json.fetch(key)
decimalify(data["value_int"], currency_lookup[data["currency"]])
decimalify(data['value_int'], currency_lookup[data['currency']])
end

def currency_lookup
{ "USD" => :usd, "BTC" => :btc, "JPY" => :jpy }
{'USD' => :usd, 'BTC' => :btc, 'JPY' => :jpy}
end

def coerce_trade(hash)
{
"tid" => hash["trade_id"],
"date" => Time.parse(hash["date"] + " UTC"),
"amount" => to_decimal("amount", hash).to_s,
"price" => to_decimal("price", hash).to_s
'tid' => hash['trade_id'],
'date' => Time.parse(hash['date'] + ' UTC'),
'amount' => to_decimal('amount', hash).to_s,
'price' => to_decimal('price', hash).to_s
}
end
end
Expand Down
2 changes: 1 addition & 1 deletion lib/mtgox/price_ticker.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,6 @@ def changed?
def unchanged?
!changed?
end
alias :unch? :unchanged?
alias_method :unch?, :unchanged?
end
end
12 changes: 6 additions & 6 deletions lib/mtgox/request.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@

module MtGox
module Request
def get(path, options={})
def get(path, options = {})
request(:get, path, options)
end

def post(path, options={})
def post(path, options = {})
request(:post, path, options)
end

Expand All @@ -33,18 +33,18 @@ def request(method, path, options)
def headers(request)
signature = Base64.strict_encode64(
OpenSSL::HMAC.digest 'sha512',
Base64.decode64(secret),
request
Base64.decode64(secret),
request
)
{'Rest-Key' => key, 'Rest-Sign' => signature}
end

def body_from_options(options)
add_nonce(options).collect{|k, v| "#{k}=#{v}"} * '&'
add_nonce(options).map { |k, v| "#{k}=#{v}" } * '&'
end

def add_nonce(options)
options.merge!({self.nonce_type => (Time.now.to_f * 1000000).to_i})
options.merge!(nonce_type => (Time.now.to_f * 1000000).to_i)
end
end
end
Loading

0 comments on commit 6ca22fd

Please sign in to comment.