Class: Spree::Currency

Inherits:
Object
  • Object
show all
Includes:
ActiveModel::Model, Comparable
Defined in:
app/models/spree/currency.rb

Overview

Virtual model for a currency. Wraps a currency code (ISO 4217) and exposes its display name and select label — the single home for that logic instead of being restated in helpers. Mirrors Spree::Locale.

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#codeString

Returns the currency code, e.g. "USD", "EUR".

Returns:

  • (String)

    the currency code, e.g. "USD", "EUR"



11
12
13
# File 'app/models/spree/currency.rb', line 11

def code
  @code
end

Instance Method Details

#<=>(other) ⇒ Object

Compare/equality by code so a Currency slots into string-keyed collections.



35
36
37
# File 'app/models/spree/currency.rb', line 35

def <=>(other)
  to_s <=> other.to_s
end

#eql?(other) ⇒ Boolean

Returns:

  • (Boolean)


39
40
41
# File 'app/models/spree/currency.rb', line 39

def eql?(other)
  other.is_a?(Spree::Currency) && to_s == other.to_s
end

#hashObject



43
44
45
# File 'app/models/spree/currency.rb', line 43

def hash
  to_s.hash
end

#labelString

Select label, e.g. "USD — United States Dollar".

Returns:

  • (String)


23
24
25
26
27
28
# File 'app/models/spree/currency.rb', line 23

def label
  upper = code.to_s.upcase
  return upper if name.blank? || name.casecmp?(code.to_s)

  "#{upper}#{name}"
end

#nameString

Display name, e.g. "United States Dollar". Falls back to the code for an unknown currency.

Returns:

  • (String)


16
17
18
19
# File 'app/models/spree/currency.rb', line 16

def name
  # `find` returns nil (it does not raise) for unknown codes.
  ::Money::Currency.find(code.to_s.upcase)&.name || code.to_s.upcase
end

#to_sObject



30
31
32
# File 'app/models/spree/currency.rb', line 30

def to_s
  code.to_s.upcase
end