Load only part of environment for rake task?

放肆的年华 提交于 2019-12-11 11:29:31

问题


I've seen a bunch of articles relating to loading the entire Rails environment for a task. However, I'm concerned that this is unnecessary because I only use two models for my task (plus the 'resque' and 'resque/scheduler'). How can I only load certain parts of an environment for my task?

Also, this question seems to be the same, but it's gotten old and no one seems to have sufficiently answered it... I'll ask now, ahead of time, that someone please give code rather than just an explanation.


回答1:


You probably won't like this answer, but...

You shouldn't load only part of your environment. Any workaround will be ugly and unpleasant and brittle. It's faster, easier, and more standard just to require your entire environment. Likely any solution you come up with will only shave one or two seconds off the startup time of the task, and it just won't be worth it for how much time and energy you've invested in making it happen.

Nevertheless, if you really want to do this, if you're only loading ActiveRecord models you can try something like this before your task:

require 'active_record'
require './app/models/my_model.rb'

You'll likely get a bunch of errors about undefined methods and missing constants. You can manually correct each one of those, requiring files one by one to correct the issue, or just take my advice and require your environment. (Hint: just require your environment.)



来源:https://stackoverflow.com/questions/9779025/load-only-part-of-environment-for-rake-task

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!