开发者

Rails. Preloading class in Development mode

What is a right way to preload Rails model in development mode?

Background: Rails 2.2, memcahe as cache store.

When Rails开发者_开发知识库 start in production mode first of all it preload and cache all models. In development mode it use laizy loading. That's why wen we store any model into rails cache, for example, Rails.cache.write("key", User.find(0)) on next loadind of app, when we try do Rails.cache.read("key") memcache fire, that User is unknown class/module. What is a right way to preload class in this situation?


You can get around this by doing something like this:

User if Rails.env == 'development'
@user = Rails.cache.fetch("key"){ User.find(0) }

This will force the User model to be re-loaded before the cache statement. If you have a class with multiple cache statements you can do this:

class SomeController
  [User, Profile, Project, Blog, Post] if Rails.env == 'development'

  def show
    @user = Rails.cache.fetch("user/#{params[:user_id]") do
      User.find(params[:user_id])
    end
  end
end

If you are in Rails 2.x and Rails.env does not work you can always use RAILS_ENV or ENV['RAILS_ENV'] instead. Of course, your other option is to simply disable caching in your development environment, then you don't have to deal with this issue at all.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜