【问题标题】:Rails mixins using ActiveSupport::Concern does not work使用 ActiveSupport::Concern 的 Rails mixins 不起作用
【发布时间】:2013-12-20 17:32:11
【问题描述】:

我在lib 文件夹中定义了以下模块/类

module Service::Log
  extend ActiveSupport::Concern

  module ClassMethods
    def logger
      Rails.logger
    end
  end
end


class Service::MyService
  include Service::Log
end

当我尝试通过对象实例调用 logger 方法时,我收到一条错误消息 - NoMethodError: undefined method `logger' for - Service::MyService:0x007fdffa0f23a0

Service::MyService.new.logger

我做错了什么?我正在使用 Rails 4.0.2

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 mixins activesupport


    【解决方案1】:

    您将记录器方法定义为类方法,而不是普通方法。这应该有效:

    module Service::Log
      extend ActiveSupport::Concern
    
      def logger
        Rails.logger
      end
    end
    
    class Service::MyService
      include Service::Log
    end
    
    Service::MyService.new.logger
    

    您之前定义方法的方式允许您直接在类上使用记录器方法,例如:

    Service::MyService.logger
    

    【讨论】:

    猜你喜欢
    • 2013-02-01
    • 2012-09-14
    • 2015-12-29
    • 1970-01-01
    • 2011-09-30
    • 2014-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多