Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Rails, how do run scripts that load the rails environment?

I have some scripts that I need to run that I want to access the full environment from my rails app.

I know I've used script/runner before in Rails 2.3.

But I've also used 'delay_job' which loads the rails environment like this (2.3 code):

#!/usr/bin/env ruby

require File.expand_path(File.join(File.dirname(__FILE__), '..', 'config', 'environment'))
require 'delayed/command'

The script I'm working on now pulls data off a message queue and then I want it to use active record and my models to insert that data into a logging database (that may or may not be the same as the DB that the rest of the app uses.

like image 645
Kevin Bedell Avatar asked Nov 22 '10 17:11

Kevin Bedell


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 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 are the environments in Rails?

Rails comes packages with 3 types of environments. Each have its own server, database, and configuration. See Rails Guides: Configuration for more information on options available to you.


1 Answers

From your script, you need to require the file config/environment.rb in your application. Note that this is exactly what DJ does here. This is true in Rails 3 as well.

Note that if you turn your script into a Rake task (which you can stick in Rakefile or in your own *.rake file in lib/tasks), you can simply have your task depend on the Rails-defined task environment.

task :mytask => :environment do
  # custom stuff
end
like image 141
yfeldblum Avatar answered Nov 15 '22 16:11

yfeldblum