lib/lotus/utils/callbacks.rb in lotus-utils-0.1.1 vs lib/lotus/utils/callbacks.rb in lotus-utils-0.2.0

- old
+ new

@@ -7,21 +7,33 @@ module Callbacks # Series of callbacks to be executed # # @since 0.1.0 # @private - class Chain < ::Array + class Chain + # Return a new chain + # + # @return [Lotus::Utils::Callbacks::Chain] + # + # @since 0.2.0 + def initialize + @chain = Array.new + end + # Adds the given callbacks to the chain # # @param callbacks [Array] one or multiple callbacks to add # @param blk [Proc] an optional block to be added # # @return [void] # + # @raise [RuntimeError] if the object was previously frozen + # # @see #run # @see Lotus::Utils::Callbacks::Callback # @see Lotus::Utils::Callbacks::MethodCallback + # @see Lotus::Utils::Callbacks::Chain#freeze # # @since 0.1.0 # # @example # require 'lotus/utils/callbacks' @@ -38,14 +50,14 @@ # # If the #notificate method accepts some argument(s) they should be passed when `run` is invoked. # chain.add :notificate def add(*callbacks, &blk) callbacks.push blk if block_given? callbacks.each do |c| - push Factory.fabricate(c) + @chain.push Factory.fabricate(c) end - uniq! + @chain.uniq! end # Runs all the callbacks in the chain. # The only two ways to stop the execution are: `raise` or `throw`. # @@ -90,12 +102,32 @@ # # chain.run(action, params) # # Those callbacks will be invoked within the context of `action`. def run(context, *args) - each do |callback| + @chain.each do |callback| callback.call(context, *args) end + end + + # It freezes the object by preventing further modifications. + # + # @since 0.2.0 + # + # @see http://ruby-doc.org/core-2.1.2/Object.html#method-i-freeze + # + # @example + # require 'lotus/utils/callbacks' + # + # chain = Lotus::Utils::Callbacks::Chain.new + # chain.freeze + # + # chain.frozen? # => true + # + # chain.add :authenticate! # => RuntimeError + def freeze + super + @chain.freeze end end # Callback factory #