Class: Hero::Observer
- Inherits:
-
Object
- Object
- Hero::Observer
- Defined in:
- lib/hero/observer.rb
Overview
Hero::Observer is designed to observe Hero::Formulas. It executes all registered steps whenever Hero::Formula#run is invoked. A Hero::Formula should only have 1 Hero::Observer attached.
Instance Attribute Summary collapse
-
#formula_name ⇒ Object
readonly
The name of the Hero::Formula being observed.
Instance Method Summary collapse
-
#add_step(*args, &block) ⇒ Object
Adds a step to be executed when the Hero::Formula is run.
-
#initialize(formula_name) ⇒ Observer
constructor
A new instance of Observer.
-
#steps ⇒ Array
All registered steps.
-
#update(context = nil, options = {}) ⇒ Object
The callback triggered when Hero::Formula#run is invoked.
Constructor Details
#initialize(formula_name) ⇒ Observer
Returns a new instance of Observer.
12 13 14 |
# File 'lib/hero/observer.rb', line 12 def initialize(formula_name) @formula_name = formula_name end |
Instance Attribute Details
#formula_name ⇒ Object (readonly)
The name of the Hero::Formula being observed.
9 10 11 |
# File 'lib/hero/observer.rb', line 9 def formula_name @formula_name end |
Instance Method Details
#add_step(*args, &block) ⇒ Object
Steps are called in the order they are added. 1st in 1st invoked.
Adds a step to be executed when the Hero::Formula is run.
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
# File 'lib/hero/observer.rb', line 47 def add_step(*args, &block) if block_given? raise ArgumentError unless args.length == 1 name = args.first step = block else raise ArgumentError if args.length > 2 if args.length == 1 step = args.first elsif args.length == 2 name = args.first step = args.last end end name ||= step.name if step.is_a? Class name ||= step.class.name steps.delete_if { |s| s.first == name } step ||= block if block_given? steps << [name, step] end |
#steps ⇒ Array
Returns All registered steps.
17 18 19 |
# File 'lib/hero/observer.rb', line 17 def steps @steps ||= [] end |
#update(context = nil, options = {}) ⇒ Object
A log message will be written to Hero.logger for each step that is called if Hero.logger has been set.
The callback triggered when Hero::Formula#run is invoked. This method runs all registered steps in order.
77 78 79 80 81 82 83 84 85 86 87 88 |
# File 'lib/hero/observer.rb', line 77 def update(context=nil, ={}) steps.each do |step| log_step(:before, step, context, ) begin step.last.call(context, ) rescue Exception => ex log_step(:error, step, context, , ex) raise ex end log_step(:after, step, context, ) end end |