开发者

When and why class and global variables should be used?

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 a开发者_如何学JAVAm 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.


Edit:

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.


Class variables can be used for a quick-and-dirty form of caching.

class Thing
  def expensiveCall
    unless @@expensiveResult
      @@expensiveResult = ['foo','bar','baz'] # or whatever
    end
    @@expensiveResult
  end
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜