ITPub博客

首页 > Linux操作系统 > Linux操作系统 > Everyone should be using low level caching in Rails

Everyone should be using low level caching in Rails

原创 Linux操作系统 作者:jieforest 时间:2012-05-20 11:24:59 0 删除 编辑

Low levelcaching is very easy to get started with in Rails 3, but it seems to be missingfrom the official guides.I personally use it all the time to help reduce the number of queries or APIcalls I’m making. Heroku has a pretty goodexplanationwhich, if you’re so far unfamiliar with low-levelcaching, is a good place to start.


Whyshould you use low level caching, and what should you use it for? Maybe youhave some data which you need regularly over multiple pages, e.g. a list ofcategories for your blog. You might want to display them on every page butthey’re not going to need to be entirely up to date for every request. Youcould stick this in controllers/application_controller.rb:


Ifyou haven’t used this style. of caching before, note that I’m calling .all on the Categoryquery. In Rails 3 ActiveRecord now uses lazy loading; it doesn’t perform. thequery until you try to use it. This is great for fragment caching in your viewsas it will prevent that query being called if a fragment cache already exists.However, if you’re using low level caching you’ll want to perform. that queryimmediately so that the results, rather than just the query object you’vebuilt, are stored in the cache.


Themainstay of low level caching in Rails is Rails.cache.fetch. There’s something you need toknow before you end up in a spiral of frustration; by defaultthis will cache in your development environment. Toremedy this, add this line to your config/environments/development.rb:

CODE:

config.cache_store = :null_store

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/301743/viewspace-730272/,如需转载,请注明出处,否则将追究法律责任。

上一篇: Python has two GILs
请登录后发表评论 登录
全部评论

注册时间:2008-04-23

  • 博文量
    443
  • 访问量
    509961