I am using Ruby on Rails 3.0.7 and I would like to know when and why class (
@@) and global (
$) variables should be used and if in this case those are properly used.
P.S.: I am asking this question because I am having the mentioned case-problem and in an answer is proposed the use of a class variable. I am grateful you can explain me if in that case it is good to use that.
The short answer is: never.
I'm new to ruby, but I do know this much from other languages: global variables are never thread-safe.
Along the same lines, avoid the singleton pattern like the plague unless you only ever deal with a unique thread.
As an aside, googling for ruby dependency injection suggests that Ruby doesn't need any of it. Well, tell you what. It does.
Because it was always assumed it doesn't, there are mountains of gems and libraries and what not out there. They basically assume you only ever have a single thread and IO blocking. Had they not done so from the start, they might have been thread safe and non-blocking instead. But currently, they just aren't.
And had they done so, they would have been playing better with event-driven servers too.
As things stand, it's a bloody mess.
Event Machine is not thread-safe. Thin and Goliath aren't by the same token. Rack-async is basically monkey patching the whole thing. Passenger uses fork and is only smart if you install REE/1.8.7 with rails. Mongrel is thread safe but IO-blocking. Webrick is single-threaded and IO blocking. The list goes on. It's just messy.