Running a Ruby script in a Rails application

I can run the following commands in the console for my Rails application and import the 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 would like to facilitate the process by simply creating a script for it. The problem is that I don’t know how to write an application specific script. To run the above commands, I need to start the console in the application folder as follows:

ruby script/console

So just copying / pasting the commands into the .rb file and failing to execute.

Any help would always be appreciated :)

+3
source share
3 answers

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

+5

, . lib/tasks/your_task.rake:

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

rake your_task. .

+2

You need to call the rails environment in the script.

Try adding this to the top of the 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 
+1
source

Source: https://habr.com/ru/post/1715438/


All Articles