Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I include helper method in service object?

I defined a helper method: MembersHelper

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

then included it in a class call Base in app/service/enum_data/base.rb file

module EnumData   
  class Base
    include MembersHelper   
  end
end

And used it from Base's subclass: GetAll in 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 an error

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

I fixed it by moving current_segment method to Base class, but I want to know why it doesn't work when I include that helper method? Did I miss something?

like image 906
bird Avatar asked Apr 12 '17 10:04

bird


1 Answers

You are using include, which makes current_segment an instance method in the including classes while what you need, is a class instance method (singleton method). In order to achieve it you should use extend:

module EnumData   
  class Base
    extend MembersHelper   
  end
end
like image 83
Andrey Deineko Avatar answered Nov 04 '22 08:11

Andrey Deineko