Alternatives to global variables - ruby

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

The Singleton Pattern might be handy for this:
https://ruby-doc.org/stdlib-2.1.0/libdoc/singleton/rdoc/Singleton.html

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

Related

Global Variables in Laravel for Views, Controllers, Models etc

I know this question has been asked before, but I am struggling to find an answer that fits my needs, or is for the most up to date version of Laravel.
Basically, I have a load of variables that will be created using data from the Route and the database. For example, I need to use the Route to set a variable called "current_page" which extracts details from the "pages" table using the unique url column. ($current_page = Page::where('url', <url-taken-from-route>)->first();)
$current_page will need to contain several relationships. There are also other global variables such as $current_site (this is a kind of multi-site environment with one home page and nested microsites) etc.
I feel the configuration files are not the right place to create these variables as a) the value of the variables can be nested and complicated and b) they are not constants but data retrieved from a database.
View Composers obviously only work with views, and a Helper class just feels too generic considering we are dealing with pages, sites, and possibly other global variables.
I gather global variables are frowned upon, but these truly are global. The values will always be the same (albeit dynamic) on every occasion, and will be required by most views and controllers.
I have also thought about putting methods in my already existing Page and Site controllers so I can call Page::current(), but am not sure putting static methods in a mostly non-static controller is the right thing to do. Also, this would make a database call every time I called Page::current() rather than having the current page stored in memory somewhere.
For now, I have created a BaseController which all other controllers extend from. I have put these variables in the constructor and manually passed them to the view in each method. (I know that is messy and doesn't work for models).
So what is the best solution here? Where to declare a global variable that can be used anywhere, but doesn't feel hacky?
Thanks

Constants class or propeties file for declaring url mappings?

Is there any strong reasons to choose one over the other when declaring the mappings for url resources?
#RequestMapping(Mappings.USER)
vs
#RequestMapping("${mappings.user}")
I understand that property files can be modified after deployment, and that might be a reason to keep it in properties if you want it to be changed easily, right? But also I think changing them easily could be undesirable. So for those with experience, which do you prefer, and why? I think a constants file might be easier to refactor, like if I wanted to change the name of a resource I would only have to refactor inside the constants class vs if I refactored properties I would have to refactor in the properties file and everywhere that uses the mapping (Im using eclipse and as far as I know it doesnt have property name refactoring like that). Or maybe a third option of neither and declaring them all as literals inside the controllers?
It all depends on your use case. If you need the change URIs without recompilation, property files is the way to go. Otherwise, constants provide type safety and ease of unit testing that SPEL doesn't. If you're not gonna change or reuse them (for example, same URI for GET and POST is very common), I don't see any need for constants at all.

Blocks vs delegates or blocks vs methods

I have just studied blocks it is good ,easy to use,helps in inline coding and keeps thing at one place .But I am not able to understand the following two points clearly.
1)How blocks are different from methods and delegates?
2)Advantages of using blocks over methods and delegates.Where are blocks more useful than delegates and methods.
Kindly explain and help me in understanding the concepts better.Thanks in advance!
A seemingly curious question as you ask:
1)How blocks are different from methods and delegates?
2)Advantages of using blocks over methods and delegates.Where are blocks more useful than delegates and methods.
After you wrote:
easy to use, helps in inline coding and keeps thing at one place
Regardless, though I maybe misunderstanding what you are after, here some further points to your own to consider in case they are helpful:
Instance methods and delegates are both associated with an instance of an object; so there is a self with instance variables, properties and other methods all of which can be referenced and used. Both come with accompanying state.
A block, like a function, is not associated with an instance of an object.
A block however differs from a function in that it can capture values and variables (those annotated with __block) from the method/function they are defined within. So they carry some state.
As to advantages of one over the others, it is really a question of picking the appropriate one for the scenario – none is "better" and the others. Decide what you need; adding behaviour to an object (method), passing an instance/method pair to provide some functionality (delegate), providing functionality based on values in the local scope (block), etc., etc.; and use the appropriate construct.
HTH

Instantiate FileSystemObject as Singleton?

I have a script with a bunch of Subs & Functions that make use of the FileSystemObject, and currently I have a local objFileSystem variable in each procedure. My initial thought was to make the procedures decoupled and reusable, but now I am wondering if I am better off with a single global scope objFileSystem?
I understand this wouldn't be a true Singleton (being VBScript), it is just the question of a single shared object vs multiple dedicated objects, which is like a Singleton.
I have recursion in a couple of places, and I am curious if that changes the best practice at all?
I have a similar condition with a Registry object, and I wonder if the best practice is the same, or do these two behave differently?
I am not (overly) concerned with performance nor memory management, but I would like to understand the Why of any best practice.
If you actually do re-use functions/procedures elsewhere and aim for strict encapsulation: stick with local instantiation of those objects. Otherwise use singleton instances. This applies to the FileSystemObject and probably to the "registry object" as well (assuming you mean a WMI object here).

Could this be a good use of global variables?

Global state is conventionally frowned upon. However, I think I can use it clientside to make my app simpler.
I have an AJAX web app that sets up several values when the user logs in - user id, as well as some other information. This info does not change for the lifetime of the app.
I also have a cache of data to minimize trips to the server.
Can I safely make all these global? (the read-only user info and the cache) I think it would make it simpler because then I wouldn't have to worry about passing the values off between functions in sometimes awkward ways.
Essentially, it'd be like constants whose values aren't known at "compile-time."
In some ways, the DOM itself serves as a form of global state - I could store a value in HTML and it would be accessible from anywhere in the program.
There's nothing wrong in using globals, if you know what you're doing. Try to keep it clean by wrapping all your "constants" in a single global object. The major concern with globals is that you're tied to a single instance of whatever state your globals store, which may or may not be a problem in your case.
You could create a namespace, this way variables would be like global, but you wouldn't have to worry too much for clashes and that kind of stuff. Facebook does that on some of it's APIs.
Just to be safe, here's an example safe namespace implementation:
if(!window.MY_NAMESPACE){
MY_NAMESPACE = {
a_variable : "some value",
a_function: function(params){
return a_variable;
},
};
}
That way you get something like global stuff, without clashing with other variables in the document (or duplicates of your script)
I think it is perfectly OK to use global state for the purposes you mentioned. Just make sure they are written to only once, i.e. not changed during execution. So try to give them names that you won't accidentally overwrite them afterwards (which is always a danger in Javascript - forgeting var and your variable becomes global, i.e. attached to the window object) and preferably put them all into the same structure, to further minimize the danger of name collisions (less names, less collisions).
Also keep in mind, that the variables are not really 'global'; if the user keeps logged in but opens a new window to your site, the 'global' variables are gone. In this case you have to ensure, that there won't be an inconsistency, i.e. the server assumes that given a user is logged in, the variables are set.

Resources