Read files in directory on ruby on rails
开发者_运维知识库I am new in ruby on rails and I want to read file names from a specified directory. Can anyone suggest code or any other links?
Thanks
I suggest you use Dir.entries("target_dir")
Check the documentation here
If you want to get all file under particular folder in array:
files = Dir.glob("#{Rails.root}/private/**/*")
#=> ["/home/demo/private/sample_test.ods", "/home/demo/private/sample_test_two.ods", "/home/demo/private/sample_test_three.ods", "/home/demo/private/sample_test_one.ods"]
If you want to pull up a filtered list of files, you can also use Dir.glob
:
Dir.glob("*.rb")
# => ["application.rb", "environment.rb"]
you can basically just get filenames with File.basename(file)
Dir.glob("path").map{ |s| File.basename(s) }
With Ruby on Rails, you should use Rails.root.join
, it’s cleaner.
files = Dir.glob(Rails.root.join(‘path’, ‘to’, ‘folder’, '*'))
Then you get an array with files path.
at first, you have to correctly create the path to your target folder
so example, when your target folder is 'models' in 'app' folder
target_folder_path = File.join(Rails.root, "/app/models")
and then this returns an array containing all of the filenames
Dir.children(target_folder_path)
also this code returns array without “.” and “..”
To list only filenames the most recommendable solution is:
irb(main)> Dir.children(Rails.root.join('app', 'models'))
=> ["user.rb", "post.rb", "comment.rb"]
If you're looking for relative paths from your Rails root folder, you can just use Dir
, such as:
Dir["app/javascript/content/**/*"]
would return, for instance:
["app/javascript/content/Rails Models.md", "app/javascript/content/Rails Routing.md"]
精彩评论