Class: FakeDynamo::Num

Inherits:
Object
  • Object
show all
Includes:
Comparable
Defined in:
lib/fake_dynamo/num.rb

Constant Summary collapse

LOW =
BigDecimal.new('-.1e126')
HIGH =
BigDecimal.new('.1e126')

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(value) ⇒ Num

Returns a new instance of Num.



10
11
12
13
# File 'lib/fake_dynamo/num.rb', line 10

def initialize(value)
  validate!(value)
  @internal = BigDecimal.new(value)
end

Instance Attribute Details

#internalObject

Returns the value of attribute internal.



6
7
8
# File 'lib/fake_dynamo/num.rb', line 6

def internal
  @internal
end

Instance Method Details

#<=>(other) ⇒ Object



39
40
41
# File 'lib/fake_dynamo/num.rb', line 39

def <=>(other)
  @internal <=> other.internal
end

#==(other) ⇒ Object



43
44
45
# File 'lib/fake_dynamo/num.rb', line 43

def ==(other)
  @internal == other.internal
end

#add(other) ⇒ Object



51
52
53
# File 'lib/fake_dynamo/num.rb', line 51

def add(other)
  return Num.new(@internal + other.internal)
end

#eql?(other) ⇒ Boolean

Returns:

  • (Boolean)


55
56
57
# File 'lib/fake_dynamo/num.rb', line 55

def eql?(other)
  self == other
end

#hashObject



47
48
49
# File 'lib/fake_dynamo/num.rb', line 47

def hash
  to_s.hash
end

#to_sObject



59
60
61
# File 'lib/fake_dynamo/num.rb', line 59

def to_s
  @internal.to_s('F').sub(/\.0$/, '')
end

#validate!(n) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/fake_dynamo/num.rb', line 15

def validate!(n)
  begin
    Float(n)
  rescue
    raise ValidationException, "The parameter cannot be converted to a numeric value: #{n}"
  end

  b = BigDecimal.new(n)
  if b < LOW
    raise ValidationException, "Number underflow. Attempting to store a number with magnitude smaller than supported range"
  end

  if b > HIGH
    raise ValidationException, "Number overflow. Attempting to store a number with magnitude larger than supported range"
  end

  significant = b.to_s('F').sub('.', '')
    .sub(/^0*/, '').sub(/0*$/, '').size

  if significant > 38
    raise ValidationException, "Attempting to store more than 38 significant digits in a Number"
  end
end