collectiveidea / interactor

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

Make the Context class swappable #174

Open fnordfish opened 5 years ago

fnordfish commented 5 years ago

This allows to have more control on how the context works. For example which attributes are required, it's default values or validation.

Here's a short sample for illustration:

class MyInteractor
  include Interactor

  self.context_class = Class.new do
    include Context::Mixin

    attr_reader :foo
    attr_accessor :my_export

    def initialize(foo: nil)
      @foo = foo
    end
  end

  def call
    if context.foo
      context.my_export = "Got: " + context.foo.to_s
    else
      context.fail!(my_export: "Error")
    end
  end
end

puts MyInteractor.call(foo: "Hi").my_export # "Got: Hi"
puts MyInteractor.call.my_export # "Error"
MyInteractor.call(unexpected: "information") # ArgumentError (unknown keyword: unexpected)

This PR probably lacks quite some documentation etc. I just wanted to get your input if this is something you'd consider. (Obviously I'm happy to put more work into this if you do)

fnordfish commented 5 years ago

Specs are failing due to the development dependency on bundler ~> 1.9 and travis has the current 2.0.2 installed on more modern rubies. That version requirement got dropped on master in 2c3d62e48dd614fc292fe0fcb1d79871fece6049