Search code examples
ruby-on-railsrubyinitializationclass-variables

When do Ruby/Rails class variables get initilalized?


I am currently facing the issue, that all my objects using an instance variable with the "same" inital value and I only read this one.

def initialize
    @available_ids = read_only_value
end

But here comes the tricky thing: This "read_only_value" is retrieved from a API. To make it easy, let's assume the value is an array of ints and gets changed once a month.

But I don't want to DoS the API by retrieving the value every time I create an object. What if I use a class variable instead?

class Foo
   @@available_ids = read_only_value
   def initialize
      @available_ids = @@available_ids //weird but let's go with it
   end
end

I assume this will solve the issue with spamming the API, since it's only execute once the variable gets initialized...

But when does this happen? When I start my Rails application, when I create the first object? Will it ever be updated? Since the value changes once a month how do I get the update?

PS: I guess the best option would be to save the ids in a database and check the ids once in a while or on demand.


Solution

  • It happens when the class is loaded (read: during Rails startup.)

    Also, you don’t need the class variable. Class instance variable is good enough:

    class Foo
       @available_ids = read_only_value
       def initialize
          @available_ids = self.class.instance_variable_get :@available_ids
       end
    end