Class: Middleman::CallbackManager

Inherits:
Object
  • Object
show all
Includes:
Contracts
Defined in:
lib/middleman-core/callback_manager.rb

Constant Summary

Constants included from Contracts

Contracts::PATH_MATCHER

Instance Method Summary collapse

Methods included from Contracts

#Contract

Constructor Details

#initializeCallbackManager

Returns a new instance of CallbackManager.



10
11
12
13
# File 'lib/middleman-core/callback_manager.rb', line 10

def initialize
  @callbacks = ::Hamster::Hash.empty
  @subscribers = ::Hamster::Vector.empty
end

Instance Method Details

#add(keys, &block) ⇒ Object



36
37
38
39
40
41
42
# File 'lib/middleman-core/callback_manager.rb', line 36

def add(keys, &block)
  immutable_keys = keys.is_a?(Symbol) ? keys : ::Hamster::Vector.new(keys)

  @callbacks = @callbacks.put(immutable_keys) do |v|
    v.nil? ? ::Hamster::Vector.new([block]) : v.push(block)
  end
end

#callbacks_for(keys) ⇒ Object



63
64
65
66
# File 'lib/middleman-core/callback_manager.rb', line 63

def callbacks_for(keys)
  immutable_keys = keys.is_a?(Symbol) ? keys : ::Hamster::Vector.new(keys)
  @callbacks.get(immutable_keys) || ::Hamster::Vector.empty
end

#execute(keys, args = [], scope = self) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
# File 'lib/middleman-core/callback_manager.rb', line 50

def execute(keys, args=[], scope=self)
  callbacks = callbacks_for(keys)
  callbacks_count = callbacks.length + @subscribers.length

  return if callbacks_count < 1

  # ::Middleman::Util.instrument "callbacks.execute", keys: keys, length: callbacks_count do
  callbacks.each { |b| scope.instance_exec(*args, &b) }
  @subscribers.each { |b| scope.instance_exec(keys, args, &b) }
  # end
end

#install_methods!(install_target, names) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/middleman-core/callback_manager.rb', line 16

def install_methods!(install_target, names)
  manager = self

  names.each do |method_name|
    install_target.define_singleton_method(method_name) do |*keys, &b|
      key_set = keys.unshift(method_name)
      manager.add(key_set.length > 1 ? key_set : key_set[0], &b)
    end
  end

  install_target.define_singleton_method(:execute_callbacks) do |*args|
    keys = args.shift
    manager.execute(keys, args[0], self)
  end

  install_target.define_singleton_method(:callbacks_for, &method(:callbacks_for))
  install_target.define_singleton_method(:subscribe_to_callbacks, &method(:subscribe))
end

#subscribe(&block) ⇒ Object



45
46
47
# File 'lib/middleman-core/callback_manager.rb', line 45

def subscribe(&block)
  @subscribers = @subscribers.push(block)
end