Rails and Threads: Constant Edition

If you’re using Rails, and threads, you know there’s certain things that are a pain.  Like all of it.

One of the things that always gets me is the whole “Object not missing constant”, which you may run into if you depend on ActiveSupport to find and load missing library/constants on first use.

For example:

Here, we’re depending on ActiveSupport to find and load the LoadMe constant/module.

In a non-threaded environment, that’s fine.  In a threaded environment, not as fine.

What happens is that the threads race to load the constant.  I think.  Sometimes.  At least they *behave* like they’re racing.  And in a race, there’s always a loser.  So you’ll get (again, *sometimes*) an error that doesn’t make any sense, like the do_something method not being found.

Regardless, that’s not really important.  What *is* important is, of course, how the hell do I fix it?

Easy.

Reference the constant before you create the threads, like so:

The first reference to LoadMe makes ActiveSupport load it.  Then the threads don’t try.

Win.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s