Module: InsalesApi::Helpers::InitApi::ClassMethods

Defined in:
lib/insales_api/helpers/init_api.rb

Instance Method Summary collapse

Instance Method Details

#init_api_for(*methods) ⇒ Object

Wraps methods into init_api block. So you can be sure that method will run for certain account.

class Account < ActiveRecord::Base
  include InsalesApi::Helpers

  def find_products_by_name(name)
    # ...
  end

  init_api_for :find_products_by_name
end

account1 = Account.find(1)
account2 = Account.find(2)

products1 = account1.find_products_by_name('smth')
products2 = account2.find_products_by_name('smth_else')

# instead of
# products1 = account1.init_api { find_products_by_name('smth') }
# products2 = account2.init_api { find_products_by_name('smth_else') }

Can be used in nessted classes like this:

class Order < ActiveRecord::Base
  extend InsalesApi::Helpers::ClassMethods

  belongs_to :account

  delegate :init_api, to: :account

  def insales_order
    InsalesApi::Order.find(insales_id)
  end

  init_api_for :insales_order
end

insales_order = Order.first.insales_order


52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/insales_api/helpers/init_api.rb', line 52

def init_api_for(*methods)
  file, line = caller.first.split(':', 2)
  methods.each do |method|
    alias_method_chain method, :init_api do |target, punct|
      class_eval <<-RUBY, file, line.to_i - 1
        def #{target}_with_init_api#{punct}(*args, &block)                # def sell_with_init_api(*args, &block)
          init_api { #{target}_without_init_api#{punct}(*args, &block) }  #   init_api { sell_without_init_api(*args, &block) }
        end                                                               # end
      RUBY
    end
  end
end