how do I run a Ruby script within the Rails framework (like I was in ./script/console)???

Hi,

Anyone know how do I run a Ruby script within the Rails framework (like I was in ./script/console)???

That is, I could do the same things I can do in the Rails console (e.g. ./script/console), however I can write a script file for this. I have scripting some data fixes in mind.

Thanks

script/runner "MyClass.my_data_fixes"

thanks - so I’m guessing then that “runner” will look in the /lib directory to try to find your file where the class exists? i.e. how does it pick up your script file path/filename?

Magic?

I'd just build the stuff in a model file.

class MyClass < ActiveRecord::Base
  def self.my_data_fixes
    # do stuff here
  end
end

Then run it like: script/runner "MyClass.my_data_fixes"

thanks - so I'm guessing then that "runner" will look in the /lib directory
to try to find your file where the class exists? i.e. how does it pick up
your script file path/filename?

# script/runner --help
Usage: script/runner [options] ('Some.ruby(code)' or a filename)

    -e, --environment=name Specifies the environment for the
runner to operate under (test/development/production).
                                     Default: development

    -h, --help Show this help message.

Another approach is Rake. I don’t do it in the model un less it’s really part of the app.

lib/tasks/setup.rake

namespace :setup do
desc “Set up initial roles in the database”

task :roles => :environment do

  # Drop any roles that might already be in the table
  puts "Removing any existing roles"
  Role.all.each do |r|
    r.destroy # forcing callbacks to cascade delete

  end
 
  puts "Creating roles..."
  Role.create :name => "User"
  Role.create :name => "Admin"

  # some other Ruby / Rails related code

end
end

rake setup:roles

The key here is that => :environment in the test declaration that brings in your Rails environment.