首页 > 解决方案 > 在 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但是,如果我更改 Publish 的代码,它会因为自动重新加载而引发错误。

标签: ruby-on-rails

解决方案


将实例创建/分配放在一个to_prepare块中。这样,它只会在生产中创建一次,但在任何时候应用程序都会在开发模式下重新加载。

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

(我会把它移到class_attribute类定义中——但如果你愿意,你也可以把它放进去to_prepare。)


推荐阅读