I have a Rails task: should I use script/runner or

2019-01-16 09:03发布

For ad hoc Rails tasks we have a few implementation alternatives, chief among which would seem to be:

script/runner some_useful_thing

and:

rake some:other_useful_thing

Which option should I prefer? If there's a clear favourite then when, if ever, should I consider using the other? If never, then why would you suppose it's still present in the framework without deprecation warnings?

8条回答
Rolldiameter
2楼-- · 2019-01-16 09:11

One thing I've done is just write normal ruby scripts and put them in the script/maintenance directory.

All you need to do to load rails and get access to all your models, etc, is put require '../../config/environment.rb' at the top of your file, then you're away.

查看更多
一纸荒年 Trace。
3楼-- · 2019-01-16 09:13

For one off commands script/runner can be fine. For anything repeated, a rake task is easier in the long-run, and has a summary if you forget what it does.

查看更多
看我几分像从前
4楼-- · 2019-01-16 09:21

Corrected based on comment 2 down. Give them the karma!

FWIW - Rails 3.0+ changes how you initialize the Rails system in a standalone script.

require File.dirname(__FILE__) + '/config/environment'

As mentioned above you can also do:

rails runner script/<script name>

Or put all the code in a Rake task, but I have a lot of legacy code from Rails 2; so I didn't want to go down that path immediately.

Each has its advantages and disadvantages.

查看更多
我命由我不由天
5楼-- · 2019-01-16 09:28

In Rails 3.0+, the config/environment.rb requires the config/application.rb, that requires the config/boot.rb.

So, to load an app in Rails 3, you still only have to require the environment.rb

查看更多
Animai°情兽
6楼-- · 2019-01-16 09:30

I got the impression script/runner was primarily for periodic tasks. E.g., a cron job that runs:

SomeClass.update_from_web('http://www.sourcefordata.gov/')
查看更多
forever°为你锁心
7楼-- · 2019-01-16 09:32

FWIW there seems to be some movement away from using script runner in favor of rake:

Update (4/25/2009): I recommend using rake tasks as opposed to script/runner for recurring tasks.

Also, as per this post you can use rake for recurring tasks just fine:

If I then wanted this to run nightly on my production database at midnight, I might write a cronjob that looks something like this:

0 0 * * * cd /var/www/apps/rails_app/ && /usr/local/bin/rake RAILS_ENV=production utils:send_expire_soon_emails

查看更多
登录 后发表回答