Is it possible to include a helper method in a service object?

I have defined a helper method: MembersHelper

module MembersHelper
 def current_segment
   Segment.where(current: true).first
 end
end

      

then included it in the call to the Base class in the app/service/enum_data/base.rb

file

module EnumData   
  class Base
    include MembersHelper   
  end
end

      

And used it from the base subclass: GetAll in the app/service/enum_data/get_all.rb

file

module EnumData
  class GetAll < Base
    def self.call
      reference_data = current_segment.entities.all
    end
  end
end

      

But I got the error

undefined local variable or method 'current_segment' for EnumData::GetByCategory:Class

I fixed it by moving the method current_segment

to the Base class, but I want to know why it doesn't work when I include this helper method? Did I miss something?

+3


source to share


1 answer


You are using include

that does current_segment

an instance method in the included classes, and what you need is an instance method of the class (singleton method). To achieve this, you must use extend

:



module EnumData   
  class Base
    extend MembersHelper   
  end
end

      

+5


source







All Articles