2011-10-11 53 views
4

我需要創建一個循環任務,從外部文本文件創建(或編輯)產品記錄。從irb內部:如何在Rails Rake任務中使用File.open?

>> f = File.open(<filename>) # file in same directory path 

沒有問題。

但是,當粘貼到Rake任務文件時,腳本總是炸彈「文件未找到」。 (Rails 3.1,Ubuntu。)

namespace :sap do 
    desc "uploads data from raw SAP file" 
    task :upload => :environment do 
    f = File.open("sap_pnlist_20111010a.csv") 
    records = f.readlines 
    records.each {|row| 
    ... etc etc ... 
    } 
    end 
end 

建議?

+6

要麼給它一個完整路徑,要麼使用['Rails.root.join'](http://apidock.com/rails/Rails/root/class),如果該文件位於Rails根目錄的某處。 –

+0

這個伎倆。感謝喬丹! –

+0

你爲什麼不讓這個答案? – Maarten

回答

4

如果該文件是你的Rails根內的某處,用

Rails.root.join('grandparent_dir', 'parent_dir', 'file.txt') 

如果該文件是不是在你的Rails根,你必須給它的完整路徑