For a recent side project a work, I found myself experimenting with Ruby on Rails to make a small database driven website. There is lots of great information around the web to help with the RoR learning curve. Still, I found myself relying most on old standby O’Reilly and their book Ruby on Rails: Up and Running. It is amazing how fast you can bring a Rails application into existence. One of the new features is scaffolding, which uses automatic code generation to create the stub methods for all your Create, Retrieve, Update, and Delete methods. For my purposes, this was almost as much as I needed. I only had to create a style-sheet for myself and create a few custom views. It was a far cry from tedious creation of identical code and endless SQL statements that I associate with my web-programming days.
Once the app was built, I needed to find a way to import lots of pre-existing data into it. Placing the data directly into the database was one option, but I was worried about bypassing Rails and all of its validations. I didn’t want to create a brand new Rails page for this either. The import would be a quick one-off, something that is ugly, but easy. As most ugly & easy things go, I probably spent more time looking up ways to do this than it would have taken me to just create a new page. One of the issues I came across here, I have been dealing with in all my Rails interactions. Rails is under constant development and there is not much documentation on the newest features.
One such feature is the script/runner interface. This can be used to run a Rails script through a cron job, or in my case from the CLI. The simple script reads in each line of a CSV file and creates a database entry for each one. There is a test mode, which validates the line, but does not save it to the database. This mode lets the user try out their data set first and fix any errors before running on the production database. I placed the script in my <rails_app>/app directory and run it as script/runner app/BulkVideoImport.rb data_file.csv
You can find my example BulkVideoImport.rb available at http://www.twopossibilities.com/wp-content/uploads/2009/06/bulkvideoimport.rb
Resources:1) http://www.ameravant.com/posts/recurring-tasks-in-ruby-on-rails-using-runner-and-cron-jobs 2)http://www.oreillynet.com/pub/a/ruby/2007/06/21/how-to-build-simple-console-apps-with-ruby-and-activerecord.html?page=1