I want to run a standalone ruby script in which I need my RoR environment to be used. Specifically, I need my models extending ActionMailer and ActiveRecord. I also need to read the database configuration from my database.yml. How do I go about it?
+5
A:
The easiest way is to change the shebang of your script from :
#!/usr/bin/ruby
to
#!/path/to/your/rails/script/runner
Et voilà, your script will be run with the full rails environment loaded. You can also run your script as ./my_script -e production
to have it run with the production database.
mat
2008-12-02 21:18:58
+1. Very Neat...
Vijay Dev
2009-12-08 05:24:02
A:
Check out this thread: http://stackoverflow.com/questions/293302/how-do-i-run-ruby-tasks-that-use-my-rails-models
Essentially it boils down to:
require "#{ENV['RAILS_ROOT']}/config/environment.rb"
Have fun!
salt.racer
2008-12-03 06:55:25
A:
I think the best way to do this is to make it a rake task.
# lib/tasks/mystuff.rake
desc 'do my stuff'
task :my_stuff => [:environment] do
# do my stuff
end
The [:environment] stanza loads the rails environment.
Scott
2008-12-03 15:48:29