Sha256: 4fdfd1398af558b3ac32a4782aa78dfb76709e2ceba859c0bf127146f1a3462b

Contents?: true

Size: 939 Bytes

Versions: 3

Compression:

Stored size: 939 Bytes

Contents

# TODO: hooks should be an inheritor
#
module Hook

  def self.append_features(base)
    base.extend self
  end

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

  def hook(name)
    name = name.to_sym

    (class << self; self; end).class_eval %{
      def #{name}(meth=nil, &blk)
        hooks[:#{name}] << (meth || blk)
      end
    }

    module_eval %{
      def #{name}(*args)
        self.class.hooks[:#{name}].each do |blk|
          if Proc === blk
            blk.call(:#{name}, *args)
          else
            __send__(blk, :#{name}, *args)
          end
        end
      end
    }
  end

end


#=begin demo

  class X
    include Hook

    hook :signal

    def boom(event, message)
      puts "Kaboom!"
    end

    signal do |event, message|
      puts "1", event, message
    end

    signal do |event, message|
      puts "2", event, message
    end

    signal :boom

  end

  X.new.signal("hi")

#=end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
facets-2.6.0 lib/more/facets/hook.rb
facets-2.5.1 lib/more/facets/hook.rb
facets-2.5.2 lib/more/facets/hook.rb