kapso
kapso

Reputation: 11903

Rails mixins using ActiveSupport::Concern does not work

I have the following module/class defined in my lib folder

module Service::Log
  extend ActiveSupport::Concern

  module ClassMethods
    def logger
      Rails.logger
    end
  end
end


class Service::MyService
  include Service::Log
end

When I try to invoke logger method via an object instance I get an error message - NoMethodError: undefined method `logger' for - Service::MyService:0x007fdffa0f23a0

Service::MyService.new.logger

What am I doing wrong? I am using Rails 4.0.2.

Upvotes: 2

Views: 1021

Answers (1)

Ju Liu
Ju Liu

Reputation: 3999

You are defining the logger method as a class method, instead of a normal method. This should work:

module Service::Log
  extend ActiveSupport::Concern

  def logger
    Rails.logger
  end
end

class Service::MyService
  include Service::Log
end

Service::MyService.new.logger

The way you were defining the method before allowed you to use the logger method on the class directly, such as:

Service::MyService.logger

Upvotes: 2

Related Questions