Class: Stellar::Price

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

Overview

reopen class

Constant Summary collapse

MAX_PRECISION =
(2**31) - 1

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.from(number) ⇒ Object

Raises:

  • (ArgumentError)


6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/stellar/price.rb', line 6

def self.from(number)
  number = BigDecimal(number, 0) if number.is_a?(String)
  number = number.to_r if number.respond_to?(:to_r)

  raise ArgumentError, "Couldn't convert #{number.class} to rational number" unless number.is_a?(Rational)

  best_r = number.rationalize(1.0e-7)

  if best_r.numerator > MAX_PRECISION || best_r.denominator > MAX_PRECISION
    raise ArgumentError, "Couldn't find valid price approximation for #{number}"
  end

  new(n: best_r.numerator, d: best_r.denominator)
end

Instance Method Details

#inspectObject



41
42
43
# File 'lib/stellar/price.rb', line 41

def inspect
  "#<Stellar::Price #{self}>"
end

#invertObject



21
22
23
# File 'lib/stellar/price.rb', line 21

def invert
  self.class.new(n: d, d: n)
end

#to_dObject



29
30
31
# File 'lib/stellar/price.rb', line 29

def to_d
  n.to_d / d
end

#to_fObject



33
34
35
# File 'lib/stellar/price.rb', line 33

def to_f
  n.to_f / d
end

#to_rObject



25
26
27
# File 'lib/stellar/price.rb', line 25

def to_r
  Rational(n, d)
end

#to_sObject



37
38
39
# File 'lib/stellar/price.rb', line 37

def to_s
  "#{n} / #{d}"
end