Created
August 12, 2010 15:19
-
-
Save zachwaugh/521133 to your computer and use it in GitHub Desktop.
Loading rails environment in a script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
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.
cool~
@lloeki your solution worked for me in rails 3.
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.
👍 require File.expand_path('../config/environment', File.dirname(__FILE__))
works (Rails 5.2)
even better: require_relative '../config/environment'
my 2 cents
rails r hello.rb
executes hello.rb
as if it is a part of rails app
@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
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.