I have inside app
a directory called csv
and inside this dir I have a file called names.csv
I want to use File.read(path:string)
function to read the file.
what is the relative path to the file?
Asked
Active
Viewed 5.5k times
43

socksocket
- 4,271
- 11
- 45
- 70
4 Answers
78
file = File.join(Rails.root, 'app', 'csv', 'names.csv')
File.read(file)

Ryan Bigg
- 106,965
- 23
- 235
- 261

tamersalama
- 4,093
- 1
- 32
- 35
-
28There's no need to use `File.join` because `Rails.root` is a `Pathname` object. Just do this: `Rails.root + "app/csv/names.csv"` – Ryan Bigg Oct 30 '12 at 20:47
-
3In particular, File.join does NOT protect you from one or more of the path parts being '..', and will happily produce a path like 'app/csv/../controllers/users_controller.rb' if given File.join(Rails.root, 'app', 'csv', '../controllers/user_controller.rb') or File.join(Rails.root, 'app', 'csv', '..', 'controllers', 'user_controller.rb') – nachbar Oct 06 '13 at 16:59
-
5To @RyanBigg's comment: Every time you use back or forward slash in a path, you make your app OS-specific. `File.join` is the safer way to go – stacker-baka Apr 09 '18 at 10:28
18
You should do: Rails.root.join "app", "csv", "names.csv"
Rails.root returns a PathName object. PathName has a join
method which takes any number of arguments and appends it to the pathname to create the new path.
Read on PathName#join here:
http://www.ruby-doc.org/stdlib-1.9.3/libdoc/pathname/rdoc/Pathname.html#method-i-join

user566245
- 4,011
- 1
- 30
- 36
9
Rails.root
points to the top folder of your rails project, so the path would be:
File.read(File.join(Rails.root, 'app','csv','names.csv'))

Laas
- 5,978
- 33
- 52
4
Thanks for above answers, It also worked this way for me:
"#{Rails.root}/public/spreadsheets/file_name.xlsx"

Atchyut Nagabhairava
- 1,295
- 3
- 16
- 23