class CoinSync::CurrencyConversionTask

Public Class Methods

new(options) click to toggle source
# File lib/coinsync/currency_conversion_task.rb, line 8
def initialize(options)
  @options = options
  @target_currency = options.currency
  @converter = options.currency_converter
end

Public Instance Methods

process_transactions(transactions) click to toggle source
# File lib/coinsync/currency_conversion_task.rb, line 14
def process_transactions(transactions)
  transactions.each do |tx|
    print '.'

    if tx.bought_currency.fiat? && tx.bought_currency != @target_currency
      tx.converted = Transaction::ConvertedAmounts.new
      tx.converted.sold_currency = tx.sold_currency
      tx.converted.sold_amount = tx.sold_amount
      tx.converted.bought_currency = @target_currency

      if tx.bought_currency.code
        tx.converted.exchange_rate = @converter.convert(
          BigDecimal.new(1),
          from: tx.bought_currency,
          to: @target_currency,
          time: tx.time
        )
        tx.converted.bought_amount = tx.bought_amount * tx.converted.exchange_rate
      else
        tx.converted.exchange_rate = nil
        tx.converted.bought_amount = BigDecimal.new(0)
      end
    elsif tx.sold_currency.fiat? && tx.sold_currency != @target_currency
      tx.converted = Transaction::ConvertedAmounts.new
      tx.converted.bought_currency = tx.bought_currency
      tx.converted.bought_amount = tx.bought_amount
      tx.converted.sold_currency = @target_currency

      if tx.sold_currency.code
        tx.converted.exchange_rate = @converter.convert(
          BigDecimal.new(1),
          from: tx.sold_currency,
          to: @target_currency,
          time: tx.time
        )
        tx.converted.sold_amount = tx.sold_amount * tx.converted.exchange_rate
      else
        tx.converted.exchange_rate = nil
        tx.converted.sold_amount = BigDecimal.new(0)
      end
    end
  end

  @converter.finalize

  puts
end