AaronLasseigne / active_interaction

:briefcase: Manage application specific business logic.
MIT License
2.06k stars 136 forks source link

Callback ordering example in docs #517

Closed omkarmoghe closed 2 years ago

omkarmoghe commented 2 years ago

I was curious how the callbacks were ordered, so I set up a simple test. Any chance we could add the ordering to the docs? I think it would be useful when developing. I didn't know that the after callback runs before the around block closes, thought that was interesting.

class Foo < ActiveInteraction::Base
  set_callback :type_check, :before, -> { puts 'before type_check' }
  set_callback :type_check, :around, ->(_i, b) { puts '>>> around type_check'; b&.call; puts "<<< around type_check" }
  set_callback :type_check, :after, -> { puts 'after type_check' }

  set_callback :validate, :before, -> { puts 'before validate' }
  set_callback :validate, :around, ->(_i, b) { puts '>>> around validate'; b&.call; puts "<<< around validate" }
  set_callback :validate, :after, -> { puts 'after validate' }

  set_callback :execute, :before, -> { puts 'before execute' }
  set_callback :execute, :around, ->(_i, b) { puts '>>> around execute'; b&.call; puts "<<< around execute" }
  set_callback :execute, :after, -> { puts 'after execute' }

  def execute
  end
end

results in

before type_check
>>> around type_check
after type_check
<<< around type_check
before validate
>>> around validate
after validate
<<< around validate
before execute
>>> around execute
after execute
<<< around execute

Not really an issue, but wasn't sure if this was PR worthy. Figured it would be easiest for someone to copy into the README if accepted.

AaronLasseigne commented 2 years ago

I'll add a note that the callbacks come from ActiveSupport::Callbacks. Whatever they do is what we do.