Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Maybe I missed this in the upgrade documentation, but if I output "Rails.root" in the rails console I see my app's root path. But if I reference "Rails.root" in a custom Rake task, it's empty. What am I missing? Thanks in advance.

Sample:

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 "".

like image 411
JP Richardson Avatar asked Dec 12 '22 19:12

JP Richardson


2 Answers

Try with join method

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

csv become a Pathname of your file.

like image 161
shingara Avatar answered Dec 28 '22 00:12

shingara


For reference:

Rails.root + "test/data.csv" 

will work as well, it's the leading slash that screws things up.

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

also works (you actually need the "leading" slash there).

like image 22
Andrew Wright Avatar answered Dec 27 '22 22:12

Andrew Wright