开发者

Access a class method from a model in the Rakefile / Ruby on Rails 3

I have a model, let's call it Foobar. I want to be able to run a cron job to update an attribute of all objects that are instances of Foobar. So, in pseudocode, it might be something like this:

Foobar.all.each do |foobar|
  foobar.update_attributes({:my_attribute => 'updated'});
end

Now, let's say I wrap that in a class method called Foobar.run_up开发者_Go百科date().

Calling Foobar.run_update() would work fine from the controller, or even from a view. But, what I want to do is run run_update() from the Rakefile so that I can tie it into a cron run. But, the Foobar class is not available to Rake when it is called from crontab.

How can I resolve that? How can I access the class methods of Foobars from Rake, when Rake is called from cron?

Thank you very much for your help.


By rake, if you mean a rake task then adding => :environment loads the rails environment for the task and you be able to call the Foobar.run_update method there. Like,

namespace :foobar do
  task :update => :environment do
    Foobar.run_update
  end
end 

And you should just be able to call rake foobar:update from the console and have it scheduled as a cronjob.


You can load up the Rails environment by requiring config/environment.rb:

ENV["RAILS_ENV"] ||= "production"
require '/where/your/rails/project/is/config/environment.rb'


In my Sinatra apps I typically have the file models/init.rb which requires Sequel, sets up my DB connection, and then uses require_relative to require all my model files. My main application then does require_relative "models/init".

With this setup any other script (including IRB) all I have to do is require the models/init.rb file myself, and I have full access to the same models and DB connection that the application has.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜