Forum: Ruby on Rails ruby script outside of rails app

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Dafd947cb43e98d7e8f432d03f4726df?d=identicon&s=25 phillee (Guest)
on 2009-05-13 10:02
(Received via mailing list)
Hello:

I would like to write a ruby script that runs on its own, but still
take advantage of the ActiveRecord configured by the web app. Is there
an easy way to do this?

Thanks in advance!
A10ba5e890803847d0ee59e178dfd8a3?d=identicon&s=25 Jeremy Olliver (Guest)
on 2009-05-13 11:29
(Received via mailing list)
Hi Phil,

you sure can. For offline tasks, I usually go with a rake task (http://
railscasts.com/episodes/127-rake-in-background) or writing a ruby
script which is executed with ruby script/runner (this makes it
similar to running script/console and typing the code yourself).

However if all you want is ActiveRecord and your db config you can do
this:

require 'rubygems'
require 'activerecord'

RAILS_ENV = (ENV["RAILS_ENV"] || "development")
RAILS_ROOT = "/location/to/my/rails_app"

# If we don't have a db connection, then parse the yml file, and
extract the db config for the relevant rails_env
unless ActiveRecord::Base.connected?
  db_options = YAML::load(File.read(File.join(RAILS_ROOT, "config",
"database.yml")))
  ActiveRecord::Base.establish_connection(db_options[RAILS_ENV])
end

You will also need to require any models you want explicitly too, if
you go this route.

Cheers,
Jeremy
Dafd947cb43e98d7e8f432d03f4726df?d=identicon&s=25 phillee (Guest)
on 2009-05-14 20:28
(Received via mailing list)
Awesome, exactly what I needed. Thank you!
This topic is locked and can not be replied to.