Class: Currency

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

Constant Summary collapse

CURRENCIES =
[
	new(840, "United States Dollar", "USD", 100),
]
CURRENCIES_BY_ID =
CURRENCIES.index_by(&:id)
CURRENCIES_BY_NAME =
CURRENCIES.index_by(&:name)
CURRENCIES_BY_CODE =
CURRENCIES.index_by(&:code)

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(id, name, code, minor_divisor) ⇒ Currency

Returns a new instance of Currency.



6
7
8
9
10
11
# File 'lib/currency.rb', line 6

def initialize(id, name, code, minor_divisor)
	@id = id
	@name = name
	@code = code
	@minor_divisor = minor_divisor
end

Instance Attribute Details

#codeObject (readonly)

Returns the value of attribute code.



4
5
6
# File 'lib/currency.rb', line 4

def code
  @code
end

#idObject (readonly)

Returns the value of attribute id.



4
5
6
# File 'lib/currency.rb', line 4

def id
  @id
end

#minor_divisorObject (readonly)

Returns the value of attribute minor_divisor.



4
5
6
# File 'lib/currency.rb', line 4

def minor_divisor
  @minor_divisor
end

#nameObject (readonly)

Returns the value of attribute name.



4
5
6
# File 'lib/currency.rb', line 4

def name
  @name
end

Class Method Details

.[](arg) ⇒ Object



46
47
48
49
50
51
52
53
# File 'lib/currency.rb', line 46

def [](arg)
	case arg
	when Integer
		CURRENCIES_BY_ID[arg]
	else
		raise ArgumentError, "invalid argument to Currency[]: #{arg.inspect}"
	end
end

.allObject



38
39
40
# File 'lib/currency.rb', line 38

def all
	CURRENCIES
end

.new(id = 840) ⇒ Object



42
43
44
# File 'lib/currency.rb', line 42

def new(id = 840)
	self[id]
end

.typecast(object) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/currency.rb', line 55

def typecast(object)
	return nil if object.nil?
	return object if object.is_a? self
	
	case object
	when Integer
		currency = CURRENCIES_BY_ID[object]
		currency.nil? ? Currency.new : currency
	when String
		currency = CURRENCIES_BY_CODE[object]
		currency.nil? ? Currency.new : currency
	else
		raise UntypecastableArgumentError, "#{object.inspect}:#{object.class} cannot be cast as #{self}"
	end
end

Instance Method Details

#convert_to_major_denomination(minor_denomination) ⇒ Object



32
33
34
35
# File 'lib/currency.rb', line 32

def convert_to_major_denomination(minor_denomination)
	return nil if minor_denomination.nil?
	minor_denomination.to_f / self.minor_divisor.to_f
end

#convert_to_minor_denomination(major_denomination) ⇒ Object



27
28
29
30
# File 'lib/currency.rb', line 27

def convert_to_minor_denomination(major_denomination)
	return nil if major_denomination.nil?
	(major_denomination.to_f * self.minor_divisor.to_f).round
end

#destroyed?Boolean

Returns:

  • (Boolean)


77
78
79
# File 'lib/currency.rb', line 77

def destroyed?
	false
end

#new_record?Boolean

Returns:

  • (Boolean)


73
74
75
# File 'lib/currency.rb', line 73

def new_record?
	false
end