Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

script/runner in rails 3

I have 2 jobs I would like to run and they are dependant on Models in my rails application. I added the ruby files in a separate folder called Jobs, that I have appended to the rail project.

Whenever I try to run them via ruby command I get the following error:

uninitialized constant Feedback (NameError).

Feedback here is a model I'm using in my rails app.

My questions: because the jobs I'm using are actually compatible with the script/runner command of rails 2, is there an alternative with Rails 3? If not how can I write ruby programs that depend on models I have in a rails app without getting the error I mentioned above.

like image 692
mabounassif Avatar asked Jun 05 '11 06:06

mabounassif


People also ask

How do I run a script in Rails?

The simplest way is with rails runner because you don't need to modify your script. runner runs Ruby code in the context of Rails non-interactively. If you make the script executable by running chmod +x script. rb , you can add #!/usr/bin/env rails runner to the top of the script, and then simply run it with ./script.

How do I run a Ruby script in Rails console?

Run source code from the editor in a console To do this, perform the following steps: Open the required Ruby file in the editor (if necessary, select a fragment of code to be executed). From the main menu, choose Tools | Load file/selection into IRB/Rails console.

What is a Rails runner?

The Rails runner allows you to run Ruby code in the Rails context non-interactively. In RubyMine, you can run and debug project or scratch Ruby scripts in the Rails context.


2 Answers

Use rails runner

$ rails -h
Usage: rails COMMAND [ARGS]
...
runner       Run a piece of code in the application environment

All commands can be run with -h for more information.
like image 195
Jakob S Avatar answered Nov 09 '22 16:11

Jakob S


The "Rails 3 way" to do this is with Rake using the :environment prerequisite, which loads the Rails environment. Like so:

task :name => :environment do |t|
  # actions
end

In the block you can load and execute your jobs.

If you haven't written Rake scripts before, here's a good tutorial. It's quite easy.

like image 43
Jordan Running Avatar answered Nov 09 '22 18:11

Jordan Running