Adnan Khan
Adnan Khan

Reputation: 917

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

Upvotes: 31

Views: 31691

Answers (8)

Pere Joan Martorell
Pere Joan Martorell

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

cercxtrova
cercxtrova

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

Flavio Wuensche
Flavio Wuensche

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

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

Erim Icel
Erim Icel

Reputation: 131

you can basically just get filenames with File.basename(file)

Dir.glob("path").map{ |s| File.basename(s) }

Upvotes: 10

Sumit Munot
Sumit Munot

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

Dylan Markow
Dylan Markow

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

Stobbej
Stobbej

Reputation: 1090

I suggest you use Dir.entries("target_dir")

Check the documentation here

Upvotes: 33

Related Questions