Kevin Bedell
Kevin Bedell

Reputation: 13424

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.

Upvotes: 10

Views: 6399

Answers (1)

yfeldblum
yfeldblum

Reputation: 65455

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

Upvotes: 9

Related Questions