Loading Your Rails Environment Into a Script

This is a fairly simple little tidbit, but still useful. Sometimes I want to have a script for my rails application, like running some reports on the data. There are two basic ways to do this: write a task(rake), or create a new ruby script file, like in the scripts directory.

If you want to do the latter, then there are two lines you my want to put at the top of your script.

ENV['RAILS_ENV'] = ARGV.first || ENV['RAILS_ENV'] || 'development'
require File.expand_path(File.dirname(__FILE__) + "/../config/environment")

The first line allows us to supply which environment we would like to run the script in. Say the script is called process.rb, we could call the script like ./process.rb production and now the environment is set to production.

The second line loads the environment file. Now all of rails, your models, libraries, and plugins are available to you.

5 thoughts on “Loading Your Rails Environment Into a Script

  1. I would use rake for doing a report or for something that should run once and be done; however, sometimes you may want to run something more intensive, something that you would want to run in the background.

    I will say that when I started off, I wrote scripts that really should have been rake tasks, but every now and then a script does the job

  2. Pingback: rufus-scheduler gem 使用笔记 » Eric Lo

  3. Pingback: Como carregar o ambiente rails num script « Roda Fixa e nerdices

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>