class Vatcalc::VATPercentage

Attributes

value[R]

Public Class Methods

new(obj) click to toggle source

Init a VATPercentage object by

=> Integer
  => VATPercentage.new 19
=> Float
  => VATPercentage.new 0.19
=> String
  =>  VATPercentage.new 19%
  =>  VATPercentage.new 19,1%
  =>  VATPercentage.new 19,1%
  =>  VATPercentage.new 19.1%
# File lib/vatcalc/vat_percentage.rb, line 18
def initialize(obj)
  @value = case obj
  when VATPercentage
    obj.value
  when 0.00..0.99
    as_d(obj.to_f + 1.00)
  when 1..100.00
    as_d((obj.to_f / 100 ) + 1.00)
  else
    if obj.is_a?(String) && obj.match(/[0-9]{0,2}\.|\,{0,1}[0-9]{0,2}/)
      as_d((obj.gsub("," , ".").to_f / 100) + 1.00)
    else
      raise TypeError.new("Can't convert #{obj.class} #{obj} to an valid #{self.class}")
    end
  end
end

Public Instance Methods

<=>(other) click to toggle source

For comparisaon between a value or a VATPercentage @return [Intger] @see module Comparable

# File lib/vatcalc/vat_percentage.rb, line 41
def <=>(other)
  to_d <=> as_d(other)
end
coerce(other) click to toggle source

@see www.mutuallyhuman.com/blog/2011/01/25/class-coercion-in-ruby Basic usage of coerce. Now you can write:

+ 10.00 * VATPercentage.new(19) + 
and:  
+ VATPercentage.new(19) * 10.00 +
# File lib/vatcalc/vat_percentage.rb, line 78
def coerce(other)
  [self,other]
end
hash() click to toggle source

Returns a Integer hash value based on the value in order to use functions like & (intersection), group_by, etc.

@return [Integer]

@example

VATPercentage.new(19).hash #=> 908351
# File lib/vatcalc/vat_percentage.rb, line 97
def hash
  [@value,self.class].hash
end
inspect() click to toggle source
# File lib/vatcalc/vat_percentage.rb, line 86
def inspect
  "#<#{self.class.name} vat_percentage:#{to_s}>"
end
to_d() click to toggle source
# File lib/vatcalc/vat_percentage.rb, line 82
def to_d
  @value
end
to_s() click to toggle source
# File lib/vatcalc/vat_percentage.rb, line 101
def to_s 
  Util.human_percentage_value(@value-1.00)
end

Private Instance Methods

as_d(num) click to toggle source
# File lib/vatcalc/vat_percentage.rb, line 107
def as_d(num)
  if num.respond_to?(:to_d)
    num.is_a?(Rational) ? num.to_d(5) : num.to_d
  else
    BigDecimal.new(num.to_s.empty? ? 0 : num.to_s)
  end
end