RoR environment in Ruby standalone script

只谈情不闲聊 提交于 2019-12-22 05:20:36

问题


I want to run a standalone ruby script in which I need my RoR environment to be used. Specifically, I need my models extending ActionMailer and ActiveRecord. I also need to read the database configuration from my database.yml. How do I go about it?


回答1:


The easiest way is to change the shebang of your script from :

#!/usr/bin/ruby

to

#!/path/to/your/rails/script/runner

Et voilà, your script will be run with the full rails environment loaded. You can also run your script as ./my_script -e production to have it run with the production database.




回答2:


Check out this thread: How do I run Ruby tasks that use my Rails models?

Essentially it boils down to:

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

Have fun!




回答3:


I think the best way to do this is to make it a rake task.

   # lib/tasks/mystuff.rake
   desc 'do my stuff'
   task :my_stuff => [:environment] do
     # do my stuff
   end

The [:environment] stanza loads the rails environment.



来源:https://stackoverflow.com/questions/335451/ror-environment-in-ruby-standalone-script

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