lib/percentable/percent.rb in percentable-0.0.1 vs lib/percentable/percent.rb in percentable-0.1.0
- old
+ new
@@ -19,13 +19,22 @@
def to_i
value.to_i
end
def coerce other
+ method = caller[0].match("`(.+)'")[1].to_sym
+
case other
when Numeric
- [to_f, other]
+ 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
@@ -39,42 +48,35 @@
def <=> other
to_f <=> other.to_f
end
- def + other
- case other
- when Percent
- self.class.new(other.value + value)
- when Numeric
- self.class.new(other + value)
- end
- end
-
def * other
case other
when Percent
- self.class.new(other.value * value)
+ self.class.new(to_f * other.value)
when Numeric
- self.class.new(other * value)
+ self.class.new(value * other)
end
end
- def - other
- case other
- when Percent
- self.class.new(value - other.value)
- when Numeric
- self.class.new(value - other)
+ [:+, :-, :/].each do |operator|
+ define_method operator do |other|
+ case other
+ when Percent
+ self.class.new(value.public_send(operator, other.value))
+ when Numeric
+ self.class.new(value.public_send(operator, other))
+ end
end
end
- def / other
- case other
- when Percent
- self.class.new(value / other.value)
+ def self.from_numeric(numeric)
+ case numeric
when Numeric
- self.class.new(value / other)
+ Percent.new(numeric*100)
+ else
+ fail TypeError, 'must inherit from Numeric'
end
end
end
end