Search code examples
ruby-on-railsrubydesign-patternsinteractorsinteractor-backend

Can I use the context as @context inside an interactor class?


In some interactors, several functions are defined to be used in call function (I'm not using utility for organize such functions).
Is it fine to use @context instead of context in this situation?

Ref URL: https://github.com/collectiveidea/interactor

Thanks for any help


Solution

  • As you can see from the source code context is just a simple accessor (getter method) declared by attr_reader:

    module Interactor
      # Internal: Install Interactor's behavior in the given class.
      def self.included(base)
        base.class_eval do
          extend ClassMethods
          include Hooks
    
          # Public: Gets the Interactor::Context of the Interactor instance.
          attr_reader :context
        end
      end
    

    There is thus almost no discernible difference between accessing the instance variable directly (@context) and through the context method as long as you're accessing it from within the class that includes this module.

    class MyInteractor
      include Interactor
    
      def my_method
        @context
        # is the exact same as 
        context
        # except for the method call
      end
    end