views:

152

answers:

3

Is there an easy way to have a rails action load up an external file of commands and then execute them?

For example, I'm trying to write a bunch of rails create methods to pre-populate a bunch of tables in a database.

Ideally, I'd like the action to check for the existence of the file, if it exists, run all of the commands, and then delete the file so it doesn't get executed again.

So, the external file would basically look like this:

MyTable.create :name => "New 1"
MyTable.create :name => "New 2"

Is this easy to accomplish in rails?

Some elaboration:

The idea would be that if a certain set up tables need to be touched up after a release, and that you can't do it through a migration script (i.e. you're initializing the database from the schema.rb file), you could:

  1. Create a file called "update_data.rb" for example
  2. Place it in an admin directory
  3. Target some action in the browser (i.e. /admin/update_data)
  4. Rails would then read in the file, executing the commands line-by-line, and then
  5. Delete the file when finished so that the actions weren't accidentally executed again

Does that help? It would be a file for one-time actions that need to be executed after a release. If there is a better method, I'm certainly all ears!

A: 

Sounds like a job for script/runner.

http://www.ameravant.com/posts/recurring-tasks-in-ruby-on-rails-using-runner-and-cron-jobs

mwilliams
+1  A: 

For step 4:

load("update_data.rb")

I believe this would load and execute your script.

pschneider
+2  A: 

Another option would be rake. You can create a new file in lib/tasks - we'll call yours bootstrap.rake

namespace :db do
  desc 'Load an initial set of data'
  task :bootstrap => :environment do
    if your_file_exists
      puts 'Loading data...'
      this_is_where_the_magic_happens        
    end
  end
end

Then from the console you can run rake db:bootstrap and schedule it with crontab if you like.

Andy Gaskell
What exactly is being represented by ':bootstrap => :environment'? I'm guessing bootstrap is the name of the task, but what does the ' => :environment' add? Does that just introduce a requirement that :environment be defined?
jerhinesmith
Calling in development mode: rake db:bootstrap production mode: rake db:bootstrap RAILS_ENV=production
Andy Gaskell
Got it, that makes sense.
jerhinesmith