在Rails中设置全局实例的最佳方法?

时间:2018-07-20 03:39:14

标签: ruby-on-rails

我有一个发布类:

class Publish
  def initialize(app_id, secret_key)
    @app_id = app_id
    @secret_key = secret_key
  end

  def publish(source_file, target_link)
    # ...
  end
end

并且我想要一个Publish的全局实例变量,所以我在初始化程序中做了一些事情:

Publish.class_eval do
  class_attribute :instance
end

Publish.instance = Publish.new(Settings.app_id, Settings.secret_key)

所以我可以在任何地方检索该实例:

Publish.instance.publish(source_file, target_link)

但是,如果我更改发布代码,则会由于自动重新加载而抛出错误undefined method 'instance' of Publish

1 个答案:

答案 0 :(得分:1)

将实例创建/分配放在to_prepare块中。这样,它将仅在生产环境中创建一次,但是在应用程序以开发模式重新加载时都可以创建。

Rails.application.config.to_prepare do
  Publish.instance = Publish.new(Settings.app_id, Settings.secret_key)
end

(我将class_attribute移到了类定义中-但如果愿意,您也可以将其放入to_prepare中。)

相关问题