Adds a readable way of expressing percentage calculations.
TL;DR
200 - 15.percent # 170module PercentageSupport
Percentage = Struct.new(:value) do
def -@
Percentage.new(-self.value)
end
def +(operand)
Percentage.new(self.value + operand.value)
end
def -(operand)
Percentage.new(self.value - operand.value)
end
def *(operand)
Percentage.new(self.value * operand)
end
def /(operand)
Percentage.new(self.value / operand)
end
def self.transform_operand(numeric, operand)
return operand unless operand.is_a? Percentage
numeric.to_d * (operand.value) / 100
end
end
def percent
Percentage.new(self.to_d)
end
def -(operand)
super(Percentage.transform_operand(self, operand))
end
def +(operand)
super(Percentage.transform_operand(self, operand))
end
def *(operand)
return operand * self if operand.is_a? Percentage
end
endMonkey patch Fixnum and Float:
Fixnum.prepend PercentageSupport
Float.prepend PercentageSupportAnd then use it like this:
325 - 10.percent # 292.5or:
adjustment = -10.percent
1900 + adjustment # 1710or
adjustment_a = -10.percent
adjustment_b = -5.percent
total_adjustment = adjustment_a + adjustment_b
100 + total_adjustment # 85or:
result = 100 - 2 * 10.percent # 80or:
100 - 10.percent / 2 # 95