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 "".
Try with join method
csv = Rails.root.join('test/data.csv')
csv become a Pathname
of your file.
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).
精彩评论