undefined function error from a module inside class in rails

Viewed 383

I have a module Helper which is present in app/models/concerns/helper.rb

module Helper
  def func
    return ['A', 'B', 'C']
  end
end

I have a class NewService which is present in app/services/pqr/new_service.rb

module PQR
  class NewService < ApplicationService
    include Helper
    @@results = func

    def self.another_func
      if @@results.blank?
        @@results = func
      end
    end
  end
end

On calling the function: PQR::NewService.another_func
I am getting the error: (undefined local variable or method func for PQR::NewService:Class)

Ruby version - 2.5.3
Rails version - 5.2.3
2 Answers

You are calling func from inside class scope; why would you expect instance-scoped methods to be accessible from there? This is an MCVE for your code

class Foo
  def func; end # instance method
  func          # class scope
end

To make func accessible, one should make it available on class level. That means, you should include your concern into singleton_class of PQR.

Contrived example:

module Foo
  def func; puts "YO"; end
end

class Bar
  class << self
    include Foo
  end

  func
end

You're including the Helper, not extending it.

e.g you're calling func in the class definition but you added it as an instance method

Basically, do

extend Helper
Related