module Vatcalc::ActsAsBillElement::ClassMethods

Public Instance Methods

acts_as_bill_element(amount:, service: false, currency: nil, vat_percentage: nil, prefix: :bill, net: false) click to toggle source
# File lib/vatcalc/acts_as_bill_element.rb, line 16
def acts_as_bill_element(amount:, service: false, currency: nil, vat_percentage: nil, prefix: :bill, net: false)

  args_to_convert = {amount: amount,currency: currency,net: net}
  delegators = [:gross,:net,:vat,:vat_splitted]

  if service
     klass  = Vatcalc::ServiceElement
  else
    klass  =  Vatcalc::BaseElement
    args_to_convert[:vat_percentage] = vat_percentage
    delegators << :vat_percentage
  end


  delegate *delegators, prefix: prefix, to: :as_vatcalc_bill_element
  v_name = :@as_vatcalc_bill_element

  define_method(:as_vatcalc_bill_element) do
    unless instance_variable_get(v_name)
      args = args_to_convert.inject({}) do |h,(k,v)|
        case v
        when Proc
          h[k] = v.call(self)
        when Symbol
          h[k] = send(v)
        else
          h[k] = v
        end
        h
      end
      instance_variable_set v_name, klass.new( args.delete(:amount), **args)
    end
    instance_variable_get(v_name)
  end
end