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 :)

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

A better solution would be to have a rake task.
In 3.0+, use rails runner path/to/script. Note: the path to your script is relative to your project root, not your working dir.
2

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.

Comments

1

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 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.