Molfar
Molfar

Reputation: 1491

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.

Upvotes: 1

Views: 116

Answers (1)

Siim Liiser
Siim Liiser

Reputation: 4348

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)

Upvotes: 2

Related Questions