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!
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!
Hi Phil,
you sure can. For offline tasks, I usually go with a rake task (http://
#127 Rake in Background - RailsCasts) 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”
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
Awesome, exactly what I needed. Thank you!
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs