Class: Delayed::Callback
- Inherits:
-
Object
- Object
- Delayed::Callback
- Defined in:
- lib/delayed/lifecycle.rb
Instance Method Summary collapse
- #add(type, &callback) ⇒ Object
- #execute(*args, &block) ⇒ Object
-
#initialize ⇒ Callback
constructor
A new instance of Callback.
Constructor Details
#initialize ⇒ Callback
Returns a new instance of Callback.
69 70 71 72 73 74 75 |
# File 'lib/delayed/lifecycle.rb', line 69 def initialize @before = [] @after = [] # Identity proc. Avoids special cases when there is no existing around chain. @around = ->(*args, &block) { block.call(*args) } end |
Instance Method Details
#add(type, &callback) ⇒ Object
90 91 92 93 94 95 96 97 98 99 100 101 102 |
# File 'lib/delayed/lifecycle.rb', line 90 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 = ->(*a, &block) { chain.call(*a) { |*b| callback.call(*b, &block) } } else raise InvalidCallback, "Invalid callback type: #{type}" end end |
#execute(*args, &block) ⇒ Object
77 78 79 80 81 82 83 84 85 86 87 88 |
# File 'lib/delayed/lifecycle.rb', line 77 def execute(*args, &block) @before.each { |c| c.call(*args) } result = @around.call(*args, &block) @after.each do |c| if c.arity == args.length + 1 # don't fail for methods that don't define `result:` c.call(*args, result: result) else c.call(*args) end end result end |