我有一个 rake 任务 loaddata.rake。
require File.join(File.dirname(__FILE__), 'load_test_data.rb')
namespace :test do
desc "Insert test data into the database"
task(:loadtest => :environment) do
puts "environment = #{RAILS_ENV}"
puts "load_test_data "; load_test_data
puts "DONE!"
end
end
我有另一个文件 load_test_data.rb 我有一些函数可以读取 csv 文件并将数据存储在数据库中。我正在从我的 rake 任务中调用该文件。
This is my load_test_data.rb
require "faster_csv"
def load_test_data
puts "test: Balance"
directory = "test/data"
name = "balances.csv"
lines = get_lines_from_csv(directory,name,"snapshot_errors")
unless lines.nil?
row_number = 1
lines.each do |row|
unless row.header_row?
begin
attributes = row.to_hash
attributes[:balance_name_id] = BalanceName.find(:first, :conditions => ["name = ?", attributes[:balance_name]]).id
attributes.delete(:balance_name)
Balance.create! attributes
rescue
store_error_in_table(row.fields.to_csv,name,row_number,"snapshot_errors")
end
row_number += 1
end
end
end
end
Rake 任务在我的这段代码中运行良好..
现在我想用延迟工作从我的 rake 任务中调用这个函数。无论如何我可以处理它吗?