Module: MotionFlux::Dispatcher

Defined in:
lib/motion_flux/dispatcher.rb

Class Method Summary collapse

Class Method Details

.add_dependency(store, depended_stores) ⇒ Object



19
20
21
22
23
# File 'lib/motion_flux/dispatcher.rb', line 19

def add_dependency store, depended_stores
  @order = nil
  dependencies[store] ||= []
  dependencies[store].concat Array.wrap(depended_stores)
end

.clearObject



25
26
27
28
# File 'lib/motion_flux/dispatcher.rb', line 25

def clear
  subscribers.clear
  dependencies.clear
end

.dependenciesObject



11
12
13
# File 'lib/motion_flux/dispatcher.rb', line 11

def dependencies
  @dependencies ||= DependencyGraph.new
end

.dispatch(action) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
# File 'lib/motion_flux/dispatcher.rb', line 30

def dispatch action
  exclusive_run action do
    ordered_subscribers(action).each do |store|
      if store.respond_to? action.message
        store.send action.message, action
      else
        puts "#{store}##{action.message} is not defined."
      end
    end
  end
end

.exclusive_run(action, &proc) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/motion_flux/dispatcher.rb', line 47

def exclusive_run action, &proc
  if @current_action
    puts 'cascading action dispatch is not allowed.'
    puts "#{@current_action} is on process."
  else
    @current_action = action
    begin
      proc.call
    ensure
      @current_action = nil
    end
  end
end

.ordered_subscribers(action) ⇒ Object



42
43
44
45
# File 'lib/motion_flux/dispatcher.rb', line 42

def ordered_subscribers action
  @order ||= dependencies.tsort.each_with_index.to_h
  subscribers[action.class].sort_by { |x| @order[x] || @order.length }
end

.register(store, action) ⇒ Object



15
16
17
# File 'lib/motion_flux/dispatcher.rb', line 15

def register store, action
  subscribers[action] << store
end

.subscribersObject



7
8
9
# File 'lib/motion_flux/dispatcher.rb', line 7

def subscribers
  @subscribers ||= Hash.new { |hash, key| hash[key] = [] }
end