Sha256: 585342291716cfdbdf1c6e64cfcaae8d23e092eeff8ec4e33b73de7e4a5b3f8b

Contents?: true

Size: 1.13 KB

Versions: 1

Compression:

Stored size: 1.13 KB

Contents

module Callback
  # The chain should have each method that has callback as key
  # and each callback points to a hash with :before, :after as key
  # each of those keys points to an array of callbacks
  # {
  #   method: {
  #     before: [...],
  #     after:  [...]
  #   }
  # }
  class Chain
    CALLBACK_HOOK = [:before, :after].freeze

    def initialize
      CALLBACK_HOOK.each do |cb_hook|
        instance_variable_set("@_#{cb_hook}_chain", new_chain)
      end
    end

    def append_callback(callback_hook, mth, callback)
      chain = get_chain(callback_hook)
      chain[mth] << callback
    end

    CALLBACK_HOOK.each do |cb_hook|
      define_method("#{cb_hook}_chain_of") do |mth_name|
        get_callbacks(cb_hook, mth_name)
      end
    end

    private

    def get_callbacks(callback_hook, mth)
      chain = get_chain(callback_hook)
      chain[mth].dup
    end

    def get_chain(callback_hook)
      instance_variable_get("@_#{callback_hook}_chain")
    end

    def new_chain
      Hash.new { |h, k| h[k] = [] }
    end
  end

  class << self
    def get_callbacks(mth)
      @_callback_chain.get_callbacks[mth]
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
action_callback-0.1.0 lib/action_callback/callback.rb