Jeremy B.
Jeremy B.

Reputation: 9216

Persistent resources in a rails app

First, this may not be the best title, but it seems to make sense at this time.

What I'm looking at is loading a resource which should live for the life of the web app. There may be some provisioning at a later point for a manual refresh, but currently that is not the case.

We have a complex permission structure which resides in the database for multiple reasons. I do not want to incur the overhead of retrieving this for each page load, thus I want it to reside in memory. My first instinct is to create a singleton which I load this into and use it whenever needed to lookup a permission. I understand the hesitance towards singletons and wonder if that is a poor approach.

I do not want to go down the route of yaml or another storage mechanism, the permissions must reside in the DB for other dependencies. That said, in Rails, what would be the most appropriate way to efficiently load and read the data?

Upvotes: 1

Views: 356

Answers (2)

loosecannon
loosecannon

Reputation: 7803

I'm not totally sure what you mean but i think there are a few ways you could go

  • caching (e.g. caches_page :page or caches_action :action in the controller )
  • or possibly storing something in a cookie/ session data, of course i don't totally understand the nature of this data so I don't Know what would work better, if at all

Upvotes: 0

Paul Alexander
Paul Alexander

Reputation: 32367

This sounds like the perfect use of the cache

permissions = Rails.cache.fetch( 'permissions' ) do
  # Permissions don't exist yet, perform long operation and load from DB
  load_permissions_from_db
end

More details here.

Upvotes: 3

Related Questions