views:

92

answers:

3

I can run the following commands in the console for my Rails application and import CSV file into my database.

require 'csv'

# row will be an array with the fields in the order they appear in the file
CSV.open('myfile.csv', 'r') do |row|
  # assuming the fields in the CSV file are in order npa, nxxFrom, nxxTo, trnk
  # create and save a Trunk model for each row
  Trunk.create!(:npa => row[0], :nxxFrom => row[1], :nxxTo => row[2], :trnk => row[3])
end

However I'd like to facilitate the process by just creating a script for it. The problem is I don't know how to write a script that is application specific. In order for the above commands to run, I need to launch console in the application folder by the following:

ruby script/console

So simply copy/pasting the commands into an .rb file and executing won't work.

Any help will always be appreciated :)

+1  A: 

You need to invoke the rails environment in the script.

Try adding this at the top of you file:

RAILS_ENV = ARGV[0] || "production"
require File.join(File.dirname(__FILE__), *%w[.. config environment])
# assumes script is placed one level below the root of the application
# second parameter is the relative path to the environment directory of your rails app
DanSingerman
+3  A: 

Why not use script/runner "<code or filename here>? to run the script? The runner script executes the script in the give application context without having a console.

Rob Di Marco
haha Rails is awesome ;) Thanks!
mr.flow3r
A better solution would be to have a rake task.
Ryan Bigg
+2  A: 

You could make it a rake task which inherits from environment. Place it into lib/tasks/your_task.rake:

task :your_task => :environment do
  # code goes here
end

Then run it using rake your_task. It can be called anything you want.

Ryan Bigg