【问题标题】:Why object_id changes after app initialization?为什么 app 初始化后 object_id 会发生变化?
【发布时间】:2021-11-03 17:00:42
【问题描述】:

导轨 6.1.4.1

我正在从初始化文件设置值,当我请求页面时,我发现配置的 object_id 已更改(并且值丢失),除非我在初始化文件中执行 require 'my_library'。我不明白为什么?

app/lib/feature_flags.rb:

class FeatureFlags
  class Configuration
    include ActiveSupport::Configurable

    config_accessor(:my_key) { false }
  end

  class << self
    def configuration
      @configuration ||= Configuration.new
    end

    def configure
      yield configuration
    end

    def enabled?(feature)
      puts "#{__FILE__} FeatureFlags.configuration.object_id = #{FeatureFlags.configuration.object_id}"

      configuration[feature]
    end
  end
end

config/initializers/feature_flags.rb:

# require 'feature_flag' # If I uncomment this line, the problem is solved

puts "#{__FILE__} FeatureFlags.configuration.object_id = #{FeatureFlags.configuration.object_id}"

FeatureFlags.configure do |config|
  config.my_key = true
end

输出:

1. Run the rails server:
config/initializers/feature_flags.rb FeatureFlags.configuration.object_id = 14720

2. Request some page:
app/lib/feature_flags.rb FeatureFlags.configuration.object_id = 22880

我的问题是:

  • 为什么我需要在初始化器中 require 'feature_flags' 以使 object_id 不改变?我认为 Zeitwerk 正在处理这个问题。
  • 这是我应该做的(正确地做)吗?

感谢您的帮助!

【问题讨论】:

  • 你可以将你的类设为Singleton "这样可以确保只能创建一个Klass实例"

标签: ruby-on-rails autoload zeitwerk


【解决方案1】:

我在这里找到了答案:https://edgeguides.rubyonrails.org/autoloading_and_reloading_constants.html#use-case-1-during-boot-load-reloadable-code

为什么不起作用:因为 FeatureFlags 是一个可重新加载的类,它会根据请求替换为新对象。

我应该如何做正确:将我的初始化代码包装在 to_prepare 块中:

Rails.application.config.to_prepare do
  FeatureFlags.configure do |config|
    config.my_key = true
  end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    相关资源
    最近更新 更多