Skip to content
This repository has been archived by the owner on Dec 29, 2024. It is now read-only.

Working With Rails

Aaron Allen edited this page Jan 26, 2020 · 1 revision

If you're working with a rails project ActiveInteractor comes bundled with some useful generators to help speed up development. You should first run the install generator with:

rails generate active_interactor:install

This will create an initializer at config/initializers/active_interactor.rb

Generators

ActiveInteractor comes bundled with some rails generators to automatically generate interactors, organizers, and contexts with:

rails generate interactor NAME [context_attributes] [options]
rails generate interactor:organizer NAME [interactor interactor] [options]
rails generate interactor:context NAME [attribute attribute] [options]

These generators will automatically create the approriate classes and matching spec or test files.

You can configure the generators in your application config with:

# config/application.rb
module MyApplication
  class Application < Rails::Application
    config.generators.interactors :active_interactor, dir: 'my_directory',
                                                      generate_context: false
    end
  end
end

The configuration supports the following options:

Option Description Default
:dir The directory interactors are generated in interactors
:generate_context Whether or not to generate a seperate context class for each interactor true

ActiveRecord Helper Methods

In some instances you may want to use an ActiveRecord model as a context for an interactor. You can do this by calling the .acts_as_context method on any ActiveRecord model, and then simply call the .contextualize_with method on your interactor or organizer to point it to the approriate class.

# app/models/user
class User < ApplicationRecord
  acts_as_context
end

# app/interactors/create_user
class CreateUser < ApplicationInteractor
  contextualize_with :user

  def perform
    context.email&.downcase!
    context.save
  end
end

CreateUser.perform(email: '[email protected]')
#=> <#User id=1 email='[email protected]'>
Clone this wiki locally