Module: SimpleDispatcher

Defined in:
lib/simpledispatcher.rb

Overview

Command dispatcher mixin

Simplifies creation of objects which can react on messages/events while using OO approach. For more complex behavior see AgentDispatcher module.

Usage

class Agent
     include Dispatcher
     @AllowedCommands = %w(start stop run)
     def initialize anId = nil;  @id = anId ; end 
     def on_run *args 
         # do some job
     end
     def on_start *args 
         # do some job
     end
     ...
end

Several options how events to the ‘agent’ can be dispatched

Agent::Dispatch *ARGV
Agent::Dispatch 'agent1', 'run', 'param1', 'param2'
Agent::Dispatch 'start'
Agent.new('agent0').dispatch *ARGV
Agent.DispatchOpts :cmd=>'start', :whatever=>'echo 42'

The ARGV variants of dispatching allows to call the ‘agent’ right away from command line, e.g.:

./agent.rb agent1 run

Another types of agents can inherit from Agent and override/add only new behavior.

Author

Viktor Zigo, 7inf.com, All rights reserved. Distributed under GNU GPL License (see LICENSE). Sponsored by: 7inf.com

History

version: 0.5

Defined Under Namespace

Modules: SimpleDispatcherClassMethods

Instance Method Summary collapse

Instance Method Details

#dispatch(*args) ⇒ Object



38
39
40
41
42
43
44
45
46
47
# File 'lib/simpledispatcher.rb', line 38

def dispatch *args
    cmd = args.shift
    # do not allow no commands - leads to user mistakes
    # cmd = self.class.AllowedCommands().first unless cmd 
    if self.class.AllowedCommands().include? cmd 
        self.send "on_#{cmd.downcase}", args
    else
        raise "Unknown command '#{cmd}', allowed commands are {#{self.class.AllowedCommands.join(',')}}"
    end
end

#dispatchOpts(opts) ⇒ Object Also known as: dispatch2



50
51
52
53
54
55
56
57
# File 'lib/simpledispatcher.rb', line 50

def dispatchOpts opts
    cmd = opts[:cmd]
    if self.class.AllowedCommands().include? cmd 
        self.send "on_#{cmd.downcase}", opts
    else
        raise "Unknown command '#{cmd}', allowed commands are {#{self.class.AllowedCommands.join(',')}}"
    end
end