Rails.root is empty in Custom Rake Task in Rails 3.0

I might have missed this in the upgrade documentation, but if I post "Rails.root" in the rails console, I can see my application root path. But if I refer to "Rails.root" in the Rake custom task, it is empty. What am I missing? Thanks in advance.

Example:

namespace :admin do desc "Import some data" task :import => :environment do csv = Rails.root + "/test/data.csv" raise "#{csv} does not exit. Stopping task." if !File.exists?(csv) CSV.foreach(csv, :headers => :first_row) do |row| puts(row['id']) end end end 

I get an exception every time because "Rails.root" is "".

+4
source share
2 answers

Try the join method

 csv = Rails.root.join('test/data.csv') 

csv will become the Pathname your file.

+12
source

For reference:

 Rails.root + "test/data.csv" 

will also work, it's a leading slash that twists things.

 "#{Rails.root}/test/data.csv" 

also works (you really need a leading slash).

+1
source

All Articles