Class: SpreeCmCommissioner::CurrencyConverter::Create

Inherits:
Object
  • Object
show all
Defined in:
app/services/spree_cm_commissioner/currency_converter/create.rb

Overview

Converts amounts between two currencies using vendor-specific exchange rates

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(vendor:, from_currency: 'USD', to_currency: 'USD') ⇒ Create

Returns a new instance of Create.



7
8
9
10
11
12
# File 'app/services/spree_cm_commissioner/currency_converter/create.rb', line 7

def initialize(vendor:, from_currency: 'USD', to_currency: 'USD')
  @vendor = vendor
  @from_currency = from_currency.upcase
  @to_currency = to_currency.upcase
  @converted_amount = nil
end

Instance Attribute Details

#converted_amountObject (readonly)

Returns the value of attribute converted_amount.



5
6
7
# File 'app/services/spree_cm_commissioner/currency_converter/create.rb', line 5

def converted_amount
  @converted_amount
end

#from_currencyObject (readonly)

Returns the value of attribute from_currency.



5
6
7
# File 'app/services/spree_cm_commissioner/currency_converter/create.rb', line 5

def from_currency
  @from_currency
end

#to_currencyObject (readonly)

Returns the value of attribute to_currency.



5
6
7
# File 'app/services/spree_cm_commissioner/currency_converter/create.rb', line 5

def to_currency
  @to_currency
end

#vendorObject (readonly)

Returns the value of attribute vendor.



5
6
7
# File 'app/services/spree_cm_commissioner/currency_converter/create.rb', line 5

def vendor
  @vendor
end

Instance Method Details

#call(amount) ⇒ Object

Converts the given amount from one currency to another



15
16
17
18
19
20
21
22
# File 'app/services/spree_cm_commissioner/currency_converter/create.rb', line 15

def call(amount)
  return amount if from_currency == to_currency || amount.zero?

  rate = vendor.exchange_rate(from_currency, to_currency)
  raise MissingCurrencyRateError, "No conversion rate from #{from_currency} to #{to_currency} for vendor #{vendor.name}" if rate.nil?

  @converted_amount = (amount * rate).round(2)
end