views:

252

answers:

4

I want to create a thread object in environment.rb and use it in some other action of some controller.

How should I do it?

Thanks in advance.

A: 

Be very careful with this. To the best of my knowledge, rails is not thread-safe. And trying to use threads safely in the face of all the magic (excuse me, "meta programming") it does sounds risky as all get out.

Why do you want a thread object anyway?

In response to the comment, saying rails is thread safe might not mean as much as you think. I's certainly be leery of counting on it at if I didn't need to.

MarkusQ
Rails has been thread-safe since 2.2.
John Topley
+3  A: 

To answer your initial question, constants declared in environment.rb are available throughout the entire codebase. Avoid doing so if you can, though; this can become configuration spaghetti pretty quickly.

More broadly, although Rails has been (from what I understand) thread-safe since version 2.2, threads are still quite uncommon - particularly in MRI - as a way to provide concurrent operation, and MRI's green threads are anyway not particularly helpful. Consider using a message queue like Starling that spins up other Ruby processes to perform asynchronous work.

Brian Guthrie
Some people call it thread safe. I wouldn't, at least not in this sense. There are too many corner cases.
MarkusQ
A: 

Further to what Brian says, consider using an initializer (put in config/initializers to have it executed). I think it makes the intent more clear than using environment.rb.

Mike Woodhouse
A: 

Actually, I want three processes to be running perpetually which are fetching some data and storing it in database. That's why I am using threads. Is there any other way to do so?