简体   繁体   English

如何运行ruby脚本,我将其放入我的Rails应用程序中的/ lib / tasks /目录中一次?

[英]How do I run a ruby script, that I put in my /lib/tasks/ directory in my Rails app, once?

Eventually I would like to get to setting it up as a Rake task and do a cron job, but for right now...all I want to do is take my ruby script that used to work as a standalone script and have it work within my Rails app. 最终我想把它设置为Rake任务并做一个cron工作,但是现在......我想要做的就是把我以前用作独立脚本的ruby脚本让它工作我的Rails应用程序。

I renamed the file to be .rake instead of .rb and tried doing rake my_script at the command-line, but that gave me this error message: 我将文件重命名为.rake而不是.rb并尝试在命令行执行rake my_script ,但这给了我这个错误消息:

rake aborted!
Don't know how to build task 'my_script'

(See full trace by running task with --trace)

How do I run this script within my Rails environment? 如何在我的Rails环境中运行此脚本?

This is the first time I am doing something like this, so any assistance would be greatly appreciated. 这是我第一次做这样的事情,所以非常感谢任何帮助。

Thanks. 谢谢。

I think what you're looking for is rails runner. 我认为你正在寻找的是rails runner。 I know in Rails 2.3.x you'd do 我知道在Rails 2.3.x中你会这样做

ruby script/runner <your file>

In Rails 3 it might be slightly different. 在Rails 3中,它可能略有不同。

http://guides.rubyonrails.org/command_line.html#rails-runner http://guides.rubyonrails.org/command_line.html#rails-runner

The primary difference between a runner and a rake task is : runner would boot rails while rake task doesn't (you can tell it to do so). 跑步者和耙子任务之间的主要区别是:跑步者会引导铁路而耙子任务没有(你可以告诉它这样做)。

Since rake can do both (boot/no boot), there's no concept of runner in rails-3 anymore. 由于rake可以同时执行(boot / no boot),因此rails-3中没有runner的概念。

So, create a rake task: whatever_name.rake 因此,创建一个rake任务: whatever_name.rake

Example: 例:

desc "This task does awesome stuff"
  task :do_awesome_stuff do
  awesome_method
end

def awesome_method
  #put your ruby code here
end

Now from your command prompt, type rake do_awesome_stuff to execute this rake task. 现在,从命令提示符处,键入rake do_awesome_stuff以执行此rake任务。

To make it boot Rails, change task definition to this: 要使其启动Rails,请将任务定义更改为:

task :do_awesome_stuff => :environment do

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM