Rails class forgets its class variables

Viewed 55

I have a class which lives in lib/my_class.rb:

class MyClass
  @@val = nil
  def self.configure(val)
    @@val = val
  end

  def self.getval
    @@val
  end
end

In config/initializers/my_class.rb:

MyClass.configure(314)
SOME_VAR = 314

However, if I open a rails console, I see the following result:

MyClass.getval
> nil
SOME_VAR
> 314
MyClass.configure(123)
MyClass.getval
> 123

What's even stranger is that, if I move MyClass.configure(314) into environment.rb, I can run MyClass.getval in a console and it returns 314 as expected. Even still, the rails server will randomly "forget" the value stored, causing me to need to restart the server. I would think that it's reloading the class file, causing it to reset its state.

I did some looking around and couldn't find any other examples of the issue. I am on Rails 6.

1 Answers

Classes in rails are ephemeral they don't need to save state after have being used. This is not a good paradigm, you must initialize your clases with the initialize method and only when you are going to access them. Also the configuration of the class must start in the initialize method

class MyClass
 attr_reader :some_var
 def initialize(:some_var)
   @some_var = some_var
 end
end

This will provide you a way to get the value by typing

my_cool_class = MyClass.new(some_var: 'This class is awesome')
# Then you can access the some var with
puts my_cool_class.some_var # Output => 'This class if fucking awesome'
Related