Class: Percentable::Percent

Inherits:
Numeric
  • Object
show all
Defined in:
lib/percentable/percent.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(value) ⇒ Percent

Returns a new instance of Percent.



3
4
5
6
7
8
9
# File 'lib/percentable/percent.rb', line 3

def initialize(value)
  if value.is_a? Percent
    @value = value.value
  else
    @value = value.to_f
  end
end

Class Method Details

.from_numeric(numeric) ⇒ Object



65
66
67
68
69
70
71
72
# File 'lib/percentable/percent.rb', line 65

def self.from_numeric(numeric)
  case numeric
  when Numeric
    Percent.new(numeric*100)
  else
    fail TypeError, 'must inherit from Numeric'
  end
end

Instance Method Details

#*(other) ⇒ Object



39
40
41
42
43
44
45
46
47
48
# File 'lib/percentable/percent.rb', line 39

def * other
  if other.is_a? Percent
    self.class.new(to_f * other.value)
  elsif other.respond_to? :coerce
    a, b = other.coerce(self)
    a * b
  else
    raise TypeError, "#{other.class} can't be coerced into Percent"
  end
end

#<=>(other) ⇒ Object



35
36
37
# File 'lib/percentable/percent.rb', line 35

def <=> other
  to_f <=> other.to_f
end

#==(other) ⇒ Object



27
28
29
# File 'lib/percentable/percent.rb', line 27

def == other
  (other.class == self.class && other.value == self.value) || other == self.to_f
end

#coerce(other) ⇒ Object



74
75
76
# File 'lib/percentable/percent.rb', line 74

def coerce other
  [CoercedPercent.new(self), other]
end

#eql?(other) ⇒ Boolean

Returns:

  • (Boolean)


31
32
33
# File 'lib/percentable/percent.rb', line 31

def eql? other
  self.send(:==, other)
end

#to_fObject



19
20
21
# File 'lib/percentable/percent.rb', line 19

def to_f
  value/100
end

#to_iObject



23
24
25
# File 'lib/percentable/percent.rb', line 23

def to_i
  value.to_i
end

#to_percentObject



61
62
63
# File 'lib/percentable/percent.rb', line 61

def to_percent
  self
end

#to_sObject



15
16
17
# File 'lib/percentable/percent.rb', line 15

def to_s
  '%g%%' % value
end

#valueObject



11
12
13
# File 'lib/percentable/percent.rb', line 11

def value
  @value ||= 0.to_f
end