在 Rails 应用程序中执行 Ruby 脚本

在 Rails 应用程序中执行 Ruby 脚本

问题描述:

我可以在控制台中为我的 Rails 应用程序运行以下命令,并将 CSV 文件导入我的数据库.

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

因此,简单地将命令复制/粘贴到 .rb 文件中并执行是行不通的.

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

任何帮助都将不胜感激:)

Any help will always be appreciated :)

为什么不使用 script/runner "? 来运行脚本?runner 脚本执行脚本在没有控制台的情况下提供应用程序上下文.

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.