Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support callbacks #115

Closed
tfausak opened this issue Jan 23, 2014 · 2 comments
Closed

Support callbacks #115

tfausak opened this issue Jan 23, 2014 · 2 comments
Assignees
Milestone

Comments

@tfausak
Copy link
Collaborator

tfausak commented Jan 23, 2014

We should support ActiveSupport::Callbacks. Tentatively, I want to say we should provide them for:

  • initialize
  • validate
  • execute (or run)

That way you could have code like this:

class Interaction < ActiveInteraction::Base
  set_callback :run, :before, -> (o)     { ... }
  set_callback :run, :after,  -> (o)     { ... }
  set_callback :run, :around, -> (o, &b) { ... }
end
@tfausak
Copy link
Collaborator Author

tfausak commented Jan 28, 2014

I wrote an MVP for this feature:

Class.new(ActiveInteraction::Base) do
  include ActiveSupport::Callbacks

  define_callbacks :initialize

  alias_method :_initialize, :initialize

  def initialize(*args, &block)
    run_callbacks(:initialize) { _initialize(*args, &block) }
  end

  set_callback :initialize, :before, -> (_)     { puts 'before' }
  set_callback :initialize, :after,  -> (_)     { puts 'after' }
  set_callback :initialize, :around, -> (_, &b) { puts '(', b.call, ')' }

  def execute; end
end.run

That returns:

before
(
{}
)
after

@tfausak
Copy link
Collaborator Author

tfausak commented Jan 29, 2014

Turns out we already support callbacks! ActiveModel gives use :validate callbacks for free.

class Interaction < ActiveInteraction::Base
  set_callback :validate, :before, lambda { |_|
    puts 'before'
  }
  set_callback :validate, :after, lambda { |_|
    puts 'after'
  }
  set_callback :validate, :around, lambda { |_, &block|
    puts 'around'
    block.call
    puts 'around'
  }

  def execute
    puts 'execute'
  end
end

Interaction.run
before
around
around
after
execute

tfausak added a commit that referenced this issue Jan 30, 2014
@ghost ghost assigned tfausak Jan 30, 2014
@tfausak tfausak closed this as completed Feb 7, 2014
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant