Class: Hero::Observer

Inherits:
Object
  • Object
show all
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

Instance Method Summary collapse

Constructor Details

#initialize(formula_name) ⇒ Observer

Returns a new instance of Observer.

Parameters:

  • formula_name (Symbol, String)

    The name of the Hero::Formula being observed.



12
13
14
# File 'lib/hero/observer.rb', line 12

def initialize(formula_name)
  @formula_name = formula_name
end

Instance Attribute Details

#formula_nameObject (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(name, step = nil, &block) ⇒ Object

Note:

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.

Examples:

A step must implement the interface.

def call(*args)

# or more specifically
def call(context, options={})

Add a step using a block.

add_step(:my_step) do |context, options|
  # logic here...
end

Add a step using an Object.

class MyStep
  def self.call(context, options={})
    # logic here...
  end
end

add_step(:my_step, MyStep)

Parameters:

  • name (Symbol, String)

    The name of the step.

  • optional (Object)

    step The step to be executed.



47
48
49
50
51
# File 'lib/hero/observer.rb', line 47

def add_step(name, step=nil, &block)
  steps.delete_if { |s| s.first == name }
  step ||= block if block_given?
  steps << [name, step]
end

#stepsArray

Returns All registered steps.

Returns:

  • (Array)

    All registered steps.



17
18
19
# File 'lib/hero/observer.rb', line 17

def steps
  @steps ||= []
end

#update(context = nil, options = {}) ⇒ Object

Note:

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.

Parameters:

  • optional (Object)

    context The context to be passed to each step.

  • optional (Hash)

    options An option Hash to be passed to each step.



60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/hero/observer.rb', line 60

def update(context=nil, options={})
  steps.each do |step|
    log_step(:info, :before, step, context, options)
    begin
      step.last.call(context, options)
    rescue Exception => ex
      log_step(:error, :after, step, context, options)
      raise ex
    end
    log_step(:info, :after, step, context, options)
  end
end