Note that there are some explanatory texts on larger screens.

plurals
  1. PORails: How to handle Thread.current data under a single-threaded server like Thin/Unicorn?
    primarykey
    data
    text
    <p>As Thin/Unicorn are single threaded, how do you handle Thread.current/per-request storage?</p> <p>Just ran a simple test - set a key in one session, read it from another -- looks like it writes/reads from the same place all the time. Doesn't happen on WEBrick though.</p> <pre><code>class TestController &lt; ApplicationController def get render text: Thread.current[:xxx].inspect end def set Thread.current[:xxx] = 1 render text: "SET to #{Thread.current[:xxx]}" end end </code></pre> <p>Tried adding <code>config.threadsafe!</code> to application.rb, no change.</p> <p>What's the right way to store per-request data?</p> <p>How come there are gems (including Rails itself, and tilt) that use Thread.current for storage? How do they overcome this problem?</p> <p>Could it be that Thread.current <em>is</em> safe per request, but just doesn't clear after request and I need to do that myself?</p> <ul> <li>Tested with Rails 3.2.9</li> </ul> <h1>Update</h1> <p>To sum up the discussion below with @skalee and @JesseWolgamott and my findings--</p> <p>Thread.current depends on the server the app is running on. Though the server might make sure no two requests run at the same time on same Thread.current, the values in this hash <strong>might not get cleared between requests</strong>, so in case of usage - initial value must be set to override last value.</p> <p>There are some well known gems who use Thread.current, like Rails, tilt and draper. I <em>guess</em> that if it was forbidden or not safe they wouldn't use it. It also seems like they all set a value before using any key on the hash (and even set it back to the original value after the request has ended).</p> <p>But overall, Thread.current is not the best practice for per-request storage. For most cases, better design will do, but for some cases, use of <code>env</code> can help. It is available in controllers, but also in middleware, and can be injected to any place in the app.</p> <p><strong>Update 2</strong> - it seems that as for now, draper is uses Thread.current incorrectly. See <a href="https://github.com/drapergem/draper/issues/390" rel="nofollow">https://github.com/drapergem/draper/issues/390</a></p> <p><strong>Update 3</strong> - that draper bug was fixed.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload