为什么 object_id 在应用程序初始化后发生变化?

Why object_id changes after app initialization?

Rails6.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

我的问题是:

感谢您的帮助!

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

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

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

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