读取 ruby​​ on rails 目录中的文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6254636/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 01:20:13  来源:igfitidea点击:

Read files in directory on ruby on rails

ruby-on-railsfilenames

提问by Adnan Khan

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?

我是 ruby​​ on rails 的新手,我想从指定的目录中读取文件名。任何人都可以建议代码或任何其他链接吗?

Thanks

谢谢

回答by Stobbej

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

我建议你使用 Dir.entries("target_dir")

Check the documentation here

检查文档here

回答by Sumit Munot

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"]

回答by Dylan Markow

If you want to pull up a filtered list of files, you can also use Dir.glob:

如果要提取过滤的文件列表,还可以使用Dir.glob

Dir.glob("*.rb")
# => ["application.rb", "environment.rb"]

回答by erimicel

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

你基本上可以得到文件名 File.basename(file)

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

回答by escanxr

With Rails, you should use Rails.root.join, it's cleaner.

使用 Rails,你应该使用Rails.root.join,它更干净。

files = Dir.glob(Rails.root.join(‘path', ‘to', ‘folder'))

files = Dir.glob(Rails.root.join(‘path', ‘to', ‘folder'))

Then you get an array with files path

然后你得到一个带有文件路径的数组

回答by Игорь Хлебников

at first, you have to correctly create the path to your target folder

首先,您必须正确创建目标文件夹的路径

so example, when your target folder is 'models' in 'app' folder

例如,当您的目标文件夹是“app”文件夹中的“models”时

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 “..”

此代码也返回没有“。”的数组 和 ”..”

回答by Flavio Wuensche

If you're looking for relative paths from your Rails root folder, you can just use Dir, such as:

如果您要从 Rails 根文件夹中查找相对路径,则可以使用Dir,例如:

Dir["app/javascript/content/**/*"]

would return, for instance:

会返回,例如:

["app/javascript/content/Rails Models.md", "app/javascript/content/Rails Routing.md"]