Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use File.open inside a Rails Rake task?

I need to create a recurring task that creates (or edits) product records from an external text file. From inside irb:

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

No issues.

But when pasted into a Rake task file, the script always bombs "File not found". (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

Suggestions?

like image 215
Brian Piercy Avatar asked Oct 11 '11 21:10

Brian Piercy


1 Answers

If the file is somewhere inside your Rails root, use

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

If the file is not in your Rails root, you must give it the full path.

like image 132
Cole Bittel Avatar answered Oct 24 '22 00:10

Cole Bittel