39

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?

socksocket
  • 4,027
  • 10
  • 40
  • 68

4 Answers4

72
file = File.join(Rails.root, 'app', 'csv', 'names.csv')
File.read(file)
Ryan Bigg
  • 105,171
  • 22
  • 229
  • 258
tamersalama
  • 3,923
  • 1
  • 29
  • 31
  • 27
    There'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
  • 3
    In 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
  • 5
    To @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
15

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
  • 3,524
  • 1
  • 29
  • 34
8

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,860
  • 31
  • 52
3

Thanks for above answers, It also worked this way for me:

"#{Rails.root}/public/spreadsheets/file_name.xlsx"
Atchyut Nagabhairava
  • 1,165
  • 3
  • 15
  • 23