lib/percentable/percent.rb in percentable-0.1.0 vs lib/percentable/percent.rb in percentable-1.0.0
- old
+ new
@@ -1,9 +1,13 @@
module Percentable
class Percent < ::Numeric
def initialize(value)
- @value = value.to_f
+ if value.is_a? Percent
+ @value = value.value
+ else
+ @value = value.to_f
+ end
end
def value
@value ||= 0.to_f
end
@@ -18,28 +22,10 @@
def to_i
value.to_i
end
- 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
-
def == other
(other.class == self.class && other.value == self.value) || other == self.to_f
end
def eql? other
@@ -68,15 +54,28 @@
self.class.new(value.public_send(operator, other))
end
end
end
+ def to_percent
+ self
+ end
+
def self.from_numeric(numeric)
case numeric
when Numeric
Percent.new(numeric*100)
else
fail TypeError, 'must inherit from Numeric'
+ end
+ end
+
+ def coerce other
+ case other
+ when Numeric
+ [AppliedPercent.new(self), other]
+ else
+ fail TypeError, "#{self.class} can't be coerced into #{other.class}"
end
end
end
end