Reputation: 1333
I have a program that will grab several global settings from an API when first logged in. These values are then used extensively throughout the program. Currently I am storing them in global variables, but it does not seem very OOP.
What are the alternatives to global variables for storing extensively used settings? Use constants? Class variables? Where would I initialize the values through the API call, since this would only need to happen once? I have seen some examples that instantiate a class to get to the variables but that does not make much sense to me.
I would like to set the values on login and after this call the variables everywhere else with a simple expression like Global.myvalue or GLOBAL_MYVALUE
Upvotes: 3
Views: 1357
Reputation: 6076
The Singleton Pattern might be handy for this:
https://ruby-doc.org/stdlib-2.1.0/libdoc/singleton/rdoc/Singleton.html
Upvotes: 1
Reputation: 1783
It's hard to give you a concise answer based on the information you provided, but I would avoid using global variables at all costs.
A good starting point would be to think of a class that could be a common ancestor to all the places where you use these variables and store them in that class. If your subclasses inherit from that class, these variables will automatically be available in their context.
Edit: like @seph posted, the singleton pattern seems to be a much better solution though
Upvotes: 0