Sha256: e7b5dcd830d991acba89d2f5f69fe9f4ec78ed9e09cc35e9729cb5bacb2afdd8

Contents?: true

Size: 1.44 KB

Versions: 4

Compression:

Stored size: 1.44 KB

Contents

module Vatcalc


  def self.acts_as_bill_element?
    @acts_as_bill_element ||= ->(obj) { obj.class.respond_to?(:acts_as_bill_element) && obj.respond_to?(:as_vatcalc_bill_element) }
  end


  module ActsAsBillElement

    def self.included(mod)
      mod.extend(ClassMethods)
    end

    module ClassMethods
      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


    end


  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
vatcalc-0.1.4 lib/vatcalc/acts_as_bill_element.rb
vatcalc-0.1.2 lib/vatcalc/acts_as_bill_element.rb
vatcalc-0.1.1 lib/vatcalc/acts_as_bill_element.rb
vatcalc-0.1.0 lib/vatcalc/acts_as_bill_element.rb