If I use a method like
def self.get_service_client
return @service_client if !@service_client.nil?
@service_client = #initialize logic
end
Now @service_client
is an instance variable of a class. How long is it in memory? Can I bank on it to not be re-initialized as long as the class is in memory (i.e like a static variable)?
Classes are instances in Ruby, too, but when you define a class the usual way, it gets assigned to a constant, and that constant is referenced by other constants, preventing its collection. So, the class will be in memory indefinitely. Since the class will remain in memory, the class instance variable will too, as the class (which is an object instance) retains a reference to its instance variables.
As an aside, the idiomatic way to do this is:
def self.get_service_client
@service_client ||= initialize_service_client
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With