Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails per-request hash?

Is there a way to cache per-request data in Rails? For a given Rails/mongrel request I have the result of a semi-expensive operation that I'd like to access several times later in that request. Is there a hash where I can store and access such data?

It needs to be fairly global and accessible from views, controllers, and libs, like Rails.cache and I18n are.

I'm ok doing some monkey-patching if that's what it takes.

  • Memcached doesn't work because it'll be shared across requests, which I don't want.
  • A global variable similarly doesn't work because different requests would share the same data, which isn't what I want.
  • Instance variables don't work because I want to access the data from inside different classes.
like image 876
Wayne Kao Avatar asked Mar 19 '09 00:03

Wayne Kao


1 Answers

There is also the request_store gem. From the documentation:

Add this line to your application's Gemfile:

gem 'request_store'

and use this code to store and retrieve data (confined to the request):

# Set
RequestStore.store[:foo] = 0

# Get
RequestStore.store[:foo]
like image 51
Alex Lang Avatar answered Sep 29 '22 00:09

Alex Lang