【问题标题】:Rails console - reload! third party services in modulesRails 控制台 - 重新加载!模块中的第三方服务
【发布时间】: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


【解决方案1】:

所以我想出了一个涉及两个初始化器的解决方案

首先,一个 000_initializer 将报告哪些机密已成功加载

module SecretChecker
  module_function

  # Return true if all secrets are present
  def secrets?(secret_list, under:)
    secret_root = Rails.application.secrets
    if under
      if under.is_a?(Array)
        secret_root = secret_root.public_send(under.shift)&.dig(*under.map(&:to_s))
      else
        secret_root = secret_root.public_send(under)
      end
      secret_list.map do |secret|
        secret_root&.dig(secret.to_s).present?
      end
    else
      secret_list.map do |secret|
        secret_root&.public_send(secret.to_s).present?
      end
    end.reduce(:&)
  end

  def check_secrets(theme, secret_list, under: nil)
    return if secrets?(secret_list, under: under)
    message = "WARNING - Missing secrets for #{theme} - #{yield}"
    puts message and Rails.logger.warn(message)
  end
end

SecretChecker.check_secrets('Slack', %i[martine], under: [:slack, :webhooks]) do
  'Slack Notifications will not work'
end

SecretChecker.check_secrets('MongoDB', %i[user password], under: :mongodb) do
  'No Database Connection if auth is activated'
end

然后,使用 ActiveSupport::Reloader 重新加载服务的模块(以 Slack 为特色的示例)

# config/initializers/0_service_activation.rb
module ServiceActivation
  def self.with_reload
    ActiveSupport::Reloader.to_prepare do
      yield
    end
  end

  module Slack
    def self.service
      ::SlackConnector
    end

    def self.should_be_activated?
      Rails.env.production? ||
      Rails.env.staging? ||
      (Rails.env.development? && ENV['ENABLE_SLACK'] == 'true')
    end

    def self.activate
      slack = service
      slack.webhook = Rails.application.secrets.slack&.dig('webhooks', 'my_webhook')
      ENV['SLACK_INTERCEPT_CHANNEL'].try do |channel|
        slack.intercept_channel = channel if channel.present?
      end
      slack.activate
      slack
    end
  end
end

[
  ...,
  ServiceActivation::Slack
] .each do |activator|
  ServiceActivation.with_reload do
    activator.activate if activator.should_be_activated?
    activator.service.status_report
  end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-15
    • 2011-02-01
    • 1970-01-01
    • 2012-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-27
    相关资源
    最近更新 更多