Reputation: 917
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
Upvotes: 31
Views: 31691
Reputation: 3112
To list only filenames the most recommendable solution is:
irb(main)> Dir.children(Rails.root.join('app', 'models'))
=> ["user.rb", "post.rb", "comment.rb"]
Upvotes: 1
Reputation: 1673
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.
Upvotes: 5
Reputation: 10336
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"]
Upvotes: 0
Reputation: 671
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 “..”
Upvotes: 2
Reputation: 131
you can basically just get filenames with File.basename(file)
Dir.glob("path").map{ |s| File.basename(s) }
Upvotes: 10
Reputation: 3868
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"]
Upvotes: 25
Reputation: 124419
If you want to pull up a filtered list of files, you can also use Dir.glob
:
Dir.glob("*.rb")
# => ["application.rb", "environment.rb"]
Upvotes: 10