【发布时间】:2017-03-18 09:19:21
【问题描述】:
我的应用连接到一些第三方 API。
我有几个 APIconnector 模块单例,它们仅在应用程序启动时初始化一次(初始化意味着客户端使用从机密检索的凭据实例化一次)
当我在控制台中reload! 应用程序时,我失去了这些服务,我必须退出并从头开始重新启动控制台。
基本上我所有的连接器都包含一个像这样的 ServiceConnector 模块
module ServiceConnector
extend ActiveSupport::Concern
included do
@activated = false
@activation_attempt = false
@client = nil
attr_reader :client, :activated
def self.client
@client ||= service_client
end
def self.service_name
name.gsub('Connector', '')
end
def self.activate
@activation_attempt = true
if credentials_present?
@client = service_client
@activated = true
end
end
这里是一个服务实现的例子
module My Connector
include ServiceConnector
@app_id = nil
@api_key = nil
def self.set_credentials(id, key)
@app_id = id
@api_key = key
end
def self.credentials_present?
@app_id.present? and @api_key.present?
end
def self.service_client
::SomeAPI::Client.new(
app_id: @app_id,
api_key: @api_key
)
end
end
我使用这种模式可以让我在 Rails 之外重用这些服务(例如 Capistrano、没有 Rails 的工作人员等)。在 Rails 中,我会以这种方式加载服务
# config/initializers/my_service.rb
if my_service_should_be_activated?
my_service.set_credentials(
Rails.application.secrets.my_service_app_id,
Rails.application.secrets.my_service_app_key
)
my_service.activate
end
我猜想执行reload! 似乎会清除我所有的实例变量,包括@client、@app_id、@api_key。
是否可以在 reload! 之后添加要执行的代码?就我而言,我需要重新运行初始化程序。或者有没有办法确保我的服务的实例变量不会在重新加载时被清除! ?
【问题讨论】:
-
也许这可以给你一些从哪里开始的灵感:gist.github.com/shime/6696842
-
哦,对不起,这个问题已经很老了,我已经找到了介于两者之间的方法。和你的很相似,会贴出来。
标签: ruby-on-rails ruby ruby-on-rails-5