Class: Percentable::Percent

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

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Numeric

#to_percent

Constructor Details

#initialize(value) ⇒ Percent

Returns a new instance of Percent.



3
4
5
# File 'lib/percentable/percent.rb', line 3

def initialize(value)
  @value = value.to_f
end

Class Method Details

.from_numeric(numeric) ⇒ Object



73
74
75
76
77
78
79
80
# File 'lib/percentable/percent.rb', line 73

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



53
54
55
56
57
58
59
60
# File 'lib/percentable/percent.rb', line 53

def * other
  case other
  when Percent
    self.class.new(to_f * other.value)
  when Numeric
    self.class.new(value * other)
  end
end

#<=>(other) ⇒ Object



49
50
51
# File 'lib/percentable/percent.rb', line 49

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

#==(other) ⇒ Object



41
42
43
# File 'lib/percentable/percent.rb', line 41

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

#coerce(other) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/percentable/percent.rb', line 23

def coerce other
  method = caller[0].match("`(.+)'")[1].to_sym

  case other
  when Numeric
    case method
    when :+
      [to_f * other, other]
    when :-
      [other, to_f * other]
    else
      [other, to_f]
    end
  else
    fail TypeError, "#{self.class} can't be coerced into #{other.class}"
  end
end

#eql?(other) ⇒ Boolean

Returns:

  • (Boolean)


45
46
47
# File 'lib/percentable/percent.rb', line 45

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

#to_fObject



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

def to_f
  value/100
end

#to_iObject



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

def to_i
  value.to_i
end

#to_sObject



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

def to_s
  '%g%%' % value
end

#valueObject



7
8
9
# File 'lib/percentable/percent.rb', line 7

def value
  @value ||= 0.to_f
end