How do I run Ruby tasks that use my Rails models?

后端 未结 9 1320
醉梦人生
醉梦人生 2021-02-01 08:58

I have a Rails app with some basic models. The website displays data retrieved from other sources. So I need to write a Ruby script that creates new instances in my database. I

9条回答
  •  失恋的感觉
    2021-02-01 09:09

    You can load the entire rails environment in any ruby script by simply requiring environment.rb:

    require "#{ENV['RAILS_ROOT']}/config/environment" 
    

    This assumes the RAILS_ROOT environment variable is set, see my comment for other ways of doing this.

    This has the added bonus of giving you all the nice classes and objects that you have in the rest of your rails code.

    To kick off your processes it sounds like cron will do what you want, and I would also add a task to your capistrano recipe that would add your script to the crontab to periodically get the data from the external source and update your DB. This can easily be done with the cronedit gem.

    The cron approach does have some drawbacks, mostly overhead and control, for other more sophisticated options see HowToRunBackgroundJobsInRails from the rails wiki.

提交回复
热议问题