Skip to content

Instantly share code, notes, and snippets.

@zachwaugh
Created August 12, 2010 15:19
Show Gist options
  • Select an option

  • Save zachwaugh/521133 to your computer and use it in GitHub Desktop.

Select an option

Save zachwaugh/521133 to your computer and use it in GitHub Desktop.
Loading rails environment in a script
#!/usr/bin/env ruby
# Load Rails
ENV['RAILS_ENV'] = ARGV[0] || 'production'
DIR = File.dirname(__FILE__)
require DIR + '/../config/environment'
# ... do stuff that requires using your rails models
@kenrett

kenrett commented Dec 14, 2013

Copy link
Copy Markdown

You just saved our lives..! Thank you so much for this... Had nearly pulled all of my hair out!

@russellsilva

Copy link
Copy Markdown

Is this current for Rails 3/4? It's my top Google result for "rails script load environment" so it might be worth updating.

@lloeki

lloeki commented Mar 28, 2014

Copy link
Copy Markdown
#!/usr/bin/env ruby
require File.expand_path('../config/environment',  __FILE__)

worked for me on Rails 3 (one-shot script located in Rails.root)

@dfwmountainbiker

Copy link
Copy Markdown

works on Rails 4 for me, but only when i run from the main Rails root. I'm sure it's based on a basic tweak I could make to have it run in a subdir, but i'm lazy today.

ghost commented Sep 20, 2014

Copy link
Copy Markdown

In Rails 4 or 3, you can try to copy the config from the file test/test_helper.rb and change the path then everything should work correctly.

@krongk

krongk commented Mar 5, 2015

Copy link
Copy Markdown

cool~

@taimoor

taimoor commented Jun 18, 2015

Copy link
Copy Markdown

@lloeki your solution worked for me in rails 3.

@giddie

giddie commented Feb 22, 2016

Copy link
Copy Markdown

FYI, I think that should be:

#!/usr/bin/env ruby

require File.expand_path('../config/environment', File.dirname(__FILE__))
# or
require "#{File.dirname(__FILE__)}/../config/environment"

Otherwise, the script will not work in the script subdirectory.

@localhostdotdev

Copy link
Copy Markdown

👍 require File.expand_path('../config/environment', File.dirname(__FILE__)) works (Rails 5.2)

@localhostdotdev

Copy link
Copy Markdown

even better: require_relative '../config/environment'

@nirname

nirname commented Apr 1, 2020

Copy link
Copy Markdown

my 2 cents

rails r hello.rb

executes hello.rb as if it is a part of rails app

@Eruanne2

Copy link
Copy Markdown

@giddie require File.expand_path('../config/environment', File.dirname(__FILE__)) worked for me too, thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment