Class: Asynchro::State
- Inherits:
-
Object
- Object
- Asynchro::State
- Defined in:
- lib/asynchro/state.rb
Instance Method Summary collapse
-
#declare(state, &block) ⇒ Object
Declares the action to be taken when a particular state is entered.
-
#declared?(state) ⇒ Boolean
Returns true if a particular state has been declared, false otherwise.
-
#initialize(&block) ⇒ State
constructor
Create a state map object.
-
#run!(state = :start) ⇒ Object
Runs a particular state, or if the state is not specified, then :start by default.
Constructor Details
#initialize(&block) ⇒ State
Create a state map object. If a block is given, it is called with the instance created, then that instance is run.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
# File 'lib/asynchro/state.rb', line 4 def initialize(&block) @states = { :finish => [ ] } if (block_given?) case (block.arity) when 0 instance_exec(&block) else block.call(self) end self.run! end end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(name, *args, &block) ⇒ Object (protected)
This lets the object instance function as a simple DSL by allowing arbitrary method names to map to various functions.
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
# File 'lib/asynchro/state.rb', line 54 def method_missing(name, *args, &block) name_s = name.to_s if (args.empty?) case (name) when /\?$/ self.declared?(name_s.sub(/\?$/, '')) when /\!$/ self.run!(name_s.sub(/\!$/, '')) else self.declare(name, &block) end else super(name, *args) end end |
Instance Method Details
#declare(state, &block) ⇒ Object
Declares the action to be taken when a particular state is entered. The argument is the state name and should be a Symbol. A block must be provided. If this state is already declared, the given block will be executed after the previous declarations.
25 26 27 |
# File 'lib/asynchro/state.rb', line 25 def declare(state, &block) (@states[state.to_sym] ||= [ ]) << block end |
#declared?(state) ⇒ Boolean
Returns true if a particular state has been declared, false otherwise.
30 31 32 |
# File 'lib/asynchro/state.rb', line 30 def declared?(state) !!@states[state] end |
#run!(state = :start) ⇒ Object
Runs a particular state, or if the state is not specified, then :start by default.
36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/asynchro/state.rb', line 36 def run!(state = :start) procs = @states[state.to_sym] case (state) when :start procs = [ lambda { finish! } ] unless (procs) end if (procs) procs.each(&:call) else STDERR.puts "WARNING: No state #{state} defined." end end |