collectiveidea / interactor

Interactor provides a common interface for performing complex user interactions.
MIT License
3.36k stars 212 forks source link

Interactors and Params #40

Closed mcansky closed 10 years ago

mcansky commented 10 years ago

Not really an issue more of a question about good practices. It's quite Rails oriented but it could be a useful discussion I believe. At least to get some feedback on how others solve or avoid these problems.

Problem 1

Interactors handle input parameters and attributes of the instance in an implicit way. Out of the blue it is difficult for a developer to see what's expected as input.

Using some comments can help :

# expected context
#  user : a User instance
#  group_id : an integer

def perform
  # .. something
end

Any advice on that ?

Problem 2

A bit of a follow up on the previous one : what if the interactor is supposed to act on one object, or an associated object to the one passed in the context and that object is not there ?

One person in my team is comparing that to validations, I would rather use the concept of before filters. As an initial test I used the setup method, fail! and a check on success? in the perform method. This does not feel right.

One way we are thinking to overcome that problem is to use a custom service object lib using Virtus (to make things easier) and Active Model validations to actually be able to specify attributes and validates them.

Ending up with something such as :

# parent class / gem
class BaseInteractor
  include Virtus
  extend ActiveModel::Naming
  include ActiveModel::Validations

  def self.perform(options = {})
    instance = self.new(options)
    if instance.valid?
      instance.perform
    else
      instance.errors
    end
  end
end

# service object
module ClassTaskInteractor
  class TestAct < BaseInteractor
    attribute :user, User
    attribute :group_id, Integer

    validates_presence_of :group_id, :user

    def perform
      true # where work should happen
    end
  end
end

Which does solve our problem but make us loose (or rewrite) some of the niceties interactor gem provides.

Any suggestions on that one ?

laserlemon commented 10 years ago

The v3 branch includes support for before/after filters that are more versatile than the existing setup method as multiple filters can be declared and/or mixed in with concerns. Validations on interactors are possible but a convention hasn't made itself obvious yet. With the new filter structure, validations should be easy to wrap up into a companion gem (interactor-validations or similar).

As for your first question, you're right that it's hard to see immediately what's expected. We haven't come up with anything better than comments yet.

I hope that helps!

mcansky commented 10 years ago

ok, I'll keep an eye out, sounds pretty good, thanks for the update !