Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 loading all models on startup

I have a class method mixed in to all my models. the method gets called when the model class is evaluated. unfortunately (for me), this seems to be on-demand, whenever the model is needed in development env. how can have rails load all the models at start up? is this even advisable?

class Foo < ActiveRecord::Base
  include Acl
  register_acl # i need this to be called for all models at start up
end

Basically, the register_acl takes a few arguments of "actions" that the model would like to be access controlled. Suppose one of the action of Foo is "manage" and the system needs to be aware of this action at start up. I think in the model is the most natural place to have this logic.

thank you!

like image 584
janechii Avatar asked Jun 12 '10 03:06

janechii


2 Answers

The correct way to do this application-wide is to turn on cache_classes in your configuration. By default it's off in development but on in production.

If you want to do it sporadically:

Rails.application.eager_load!
like image 89
sj26 Avatar answered Nov 15 '22 16:11

sj26


I dont know if this is ideal, but it works for me. Somewhere in the config/initialize/, i do this:

Dir.glob("#{Rails.root}/app/models/*.rb").sort.each { |file| require_dependency file }

and that preloads my models

like image 44
janechii Avatar answered Nov 15 '22 16:11

janechii