【问题标题】:Rails: NameError with lib moduleRails:带有 lib 模块的 NameError
【发布时间】:2016-02-28 13:51:38
【问题描述】:

在我的设备模型中,我尝试在 lib 类上调用类方法,但在生产中我得到了一个

NameError (uninitialized constant Device::Push):

不过,它在开发中起作用。

但我不调用 Device::Push 类。相反,这就是我在我的设备模型中所做的:

class Device < ActiveRecord::Base
  ...
  after_update :send_notifications
  ...
  def send_notifications
    Push::NotificationFactory.send(device: self) if (self.push_token_changed? && ! self.push_token.nil?)
  end
end

并且在 lib/push/notification_factory.rb 中应该调用以下类:

module Push
  class NotificationFactory
    def self.send(device: )
      n = Rpush::Apns::Notification.new
      n.app = Rpush::Apns::App.find_by_name(Rails.configuration.x.app['push']['app_name'])
      n.device_token = device.push_token
      n.alert = 'Welcome to PrizeArena!'
      n.save!
    end
  end
end

这是我收到的错误消息:

2016-02-28T13:40:51.407542+00:00 app[web.1]: NameError (uninitialized constant Device::Push):
2016-02-28T13:40:51.407543+00:00 app[web.1]:   app/models/device.rb:77:in `send_notifications'
2016-02-28T13:40:51.407544+00:00 app[web.1]:   app/controllers/api/v1/users_controller.rb:44:in `update'

如果有人能指出 NameError 的来源,那就太好了。

【问题讨论】:

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


    【解决方案1】:

    我发现了为什么它在开发中起作用但在生产中不起作用的问题。

    我正在将 lib 添加到 auto_load 路径,但需要将其添加到 eager_load_path。

    你需要添加

    config.eager_load_paths &lt;&lt; Rails.root.join('lib')

    到 application.rb

    问题只发生在生产环境,而不是开发环境,因为在生产环境中 Rails 默认会加载环境。

    更多信息在这里: http://blog.arkency.com/2014/11/dont-forget-about-eager-load-when-extending-autoload/

    【讨论】:

      【解决方案2】:

      NameError(未初始化的常量 Device::Push)

      您需要使用includemodule 嵌入class

      class Device < ActiveRecord::Base
      
        include Push
        ...
        after_update :send_notifications
        ...
        def send_notifications
          Push::NotificationFactory.send(device: self) if (self.push_token_changed? && ! self.push_token.nil?)
        end
      end
      

      【讨论】:

      • 谢谢,我刚刚发现这是一个生产环境问题,并且由于 Rails eager_loading 生产环境。
      猜你喜欢
      • 2012-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-23
      • 2018-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多