Module: Vatcalc::ActsAsBillElement::ClassMethods

Defined in:
lib/vatcalc/acts_as_bill_element.rb

Instance Method Summary collapse

Instance Method Details

#acts_as_bill_element(amount:, service: false, currency: nil, vat_percentage: nil, prefix: :bill, net: false) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# 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