Ruby独立脚本中的RoR环境

时间:2021-05-21 23:33:18

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?

我想运行一个独立的ruby脚本,我需要使用我的RoR环境。具体来说,我需要扩展ActionMailer和ActiveRecord的模型。我还需要从database.yml中读取数据库配置。我该怎么办?

3 个解决方案

#1


9  

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

最简单的方法是从以下位置更改脚本的shebang:

#!/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.

Etvoilà,您的脚本将在加载完整的rails环境的情况下运行。您还可以将脚本作为./my_script -e production运行,以使其与生产数据库一起运行。

#2


0  

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

看看这个主题:如何运行使用我的Rails模型的Ruby任务?

Essentially it boils down to:

基本上它归结为:

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

Have fun!

#3


0  

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.

[:environment]节加载rails环境。

#1


9  

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

最简单的方法是从以下位置更改脚本的shebang:

#!/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.

Etvoilà,您的脚本将在加载完整的rails环境的情况下运行。您还可以将脚本作为./my_script -e production运行,以使其与生产数据库一起运行。

#2


0  

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

看看这个主题:如何运行使用我的Rails模型的Ruby任务?

Essentially it boils down to:

基本上它归结为:

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

Have fun!

#3


0  

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.

[:environment]节加载rails环境。