简体   繁体   English

使用 Ruby 中的 class 变量克隆 Class

[英]Clone Class with class variables in Ruby

I have some third party class , which extensive uses class variables:我有一些第三方 class ,它广泛使用 class 变量:

class Config
  def default_locale
    @@default_locale ||= :en
  end
end

This class (I18n::Config) is quit large, and there are a lot of class variables.这个 class (I18n::Config) 退出大,有很多 class 变量。 It is not a case to completely rewrite it.完全重写它不是一个案例。

I need to get an instance of this class, which will not affect anyway original Config class variables.我需要获取此 class 的实例,这不会影响原始配置 class 变量。

This is needed for Rails app, where I try to make I18n configurable per each request and thread safe at the same time.这对于 Rails 应用程序来说是必需的,我尝试让 I18n 可以根据每个请求进行配置,并且同时保证线程安全

For thread safety I will use RequestStore .为了线程安全,我将使用RequestStore I need to put there an independent Config instance, which will not affect original class variables.我需要放一个独立的 Config 实例,它不会影响原来的 class 变量。

Call.dup on the class to get an identical, but independent anonymous class that can be initiated.在 class 上调用.dup 以获得可以启动的相同但独立的匿名 class。

config1 = I18n.config
config2 = I18n::Config.new # same class
config3 = I18n::Config.dup.new # different class
config1.default_locale # :en
config2.default_locale # :en
config3.default_locale # :en

config2.default_locale = :de

config1.default_locale # :de
config2.default_locale # :de
config3.default_locale # :en (unchanged)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM