Class: Commissioner::Calculator

Inherits:
Object
  • Object
show all
Defined in:
lib/commissioner/calculator.rb

Constant Summary collapse

AmountUnknown =
Class.new(StandardError)
CommissionerArityInvalid =
Class.new(StandardError)

Instance Method Summary collapse

Constructor Details

#initialize(params, config:, order: DEFAULT_ORDER) ⇒ Calculator

Returns a new instance of Calculator.



81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/commissioner/calculator.rb', line 81

def initialize(params, config:, order: DEFAULT_ORDER)
  @charged_amount = guess_amount(params[:charged_amount], params[:charged_currency])
  @received_amount = guess_amount(params[:received_amount], params[:received_currency])

  @exchange_commission = params[:exchange_commission] || 0
  @commission = params[:commission] || 0

  unless config.exchanger.is_a?(Proc) && config.exchanger.arity == 3
    raise CommissionerArityInvalid, "'exchanger' setting must be a lambda with arity of 3"
  end

  @exchanger = config.exchanger
  @order = order
  @rounding_mode =
    case config.rounding_mode
    when :up
      BigDecimal::ROUND_UP
    when :down
      BigDecimal::ROUND_DOWN
    when :half_even
      BigDecimal::ROUND_HALF_EVEN
    else
      BigDecimal::ROUND_HALF_UP
    end
end

Instance Method Details

#calculateObject



107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
# File 'lib/commissioner/calculator.rb', line 107

def calculate
  @result = OpenStruct.new(
    received_amount: @received_amount,
    charged_amount: @charged_amount,
    fee: 0,
    exchange_fee: 0,
    exchange_rate: 0
  )

  if !empty?(@charged_amount) && @received_amount.zero?
    calculate_for_charged
  elsif !empty?(@received_amount) && @charged_amount.zero?
    calculate_for_received
  else
    raise AmountUnknown, HELP_MESSAGE
  end

  @result
end