Class: Delayed::Callback

Inherits:
Object
  • Object
show all
Defined in:
lib/delayed/lifecycle.rb

Instance Method Summary collapse

Constructor Details

#initializeCallback

Returns a new instance of Callback.



56
57
58
59
60
61
62
# File 'lib/delayed/lifecycle.rb', line 56

def initialize
  @before = []
  @after = []

  # Identity proc. Avoids special cases when there is no existing around chain.
  @around = lambda { |*args, &block| block.call(*args) }
end

Instance Method Details

#add(type, &callback) ⇒ Object



71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/delayed/lifecycle.rb', line 71

def add(type, &callback)
  case type
  when :before
    @before << callback
  when :after
    @after << callback
  when :around
    chain = @around # use a local variable so that the current chain is closed over in the following lambda
    @around = lambda { |*a, &block| chain.call(*a) { |*b| callback.call(*b, &block) } }
  else
    raise InvalidCallback, "Invalid callback type: #{type}"
  end
end

#execute(*args, &block) ⇒ Object



64
65
66
67
68
69
# File 'lib/delayed/lifecycle.rb', line 64

def execute(*args, &block)
  @before.each { |c| c.call(*args) }
  result = @around.call(*args, &block)
  @after.each { |c| c.call(*args) }
  result
end