module MotionFlux::Dispatcher

Public Instance Methods

add_dependency(store, depended_stores) click to toggle source
# 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
clear() click to toggle source
# File lib/motion_flux/dispatcher.rb, line 25
def clear
  subscribers.clear
  dependencies.clear
end
dependencies() click to toggle source
# File lib/motion_flux/dispatcher.rb, line 11
def dependencies
  @dependencies ||= DependencyGraph.new
end
dispatch(action) click to toggle source
# 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) click to toggle source
# 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) click to toggle source
# 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) click to toggle source
# File lib/motion_flux/dispatcher.rb, line 15
def register store, action
  subscribers[action] << store
end
subscribers() click to toggle source
# File lib/motion_flux/dispatcher.rb, line 7
def subscribers
  @subscribers ||= Hash.new { |hash, key| hash[key] = [] }
end