简体   繁体   中英

Clone Class with class variables in Ruby

I have some third party class , which extensive uses class variables:

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

This is needed for Rails app, where I try to make I18n configurable per each request and thread safe at the same time.

For thread safety I will use RequestStore . I need to put there an independent Config instance, which will not affect original class variables.

Call.dup on the class to get an identical, but independent anonymous class that can be initiated.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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