如何从模型方法访问公用文件夹?

时间:2014-01-13 16:42:31

标签: ruby-on-rails ruby

我想在模型中做这样的事情,使用公共文件夹,比如db for files。

all_images = []
(1..100).each do |image_number|
   if File.exists?("/img/#{image_number}.jpg")
      # add image path to the list
   end
end

Rails有没有办法以这种方式“查看”公共目录中的文件?

4 个答案:

答案 0 :(得分:3)

如果您使用asset pipeline并且想要检查资产是否存在,请在资产文件夹中查找:

 all_images = 1.upto(100).map do |image_number|
   path = Rails.root.join("assets/images/#{image_number}.jpg")
   path if File.exists?(path)
 end.compact

如果您拥有public文件夹中的资产,不建议(出于各种原因),除非您使用Rails< 3和/或自己构建一些资产管理扩展,你可以在那里寻找:

 all_images = 1.upto(100).map do |image_number|
   path = Rails.root.join("public/img/#{image_number}.jpg")
   path if File.exists?(path)
 end.compact

答案 1 :(得分:0)

您可以使用Rails.root.join('public', 'img', '1.jpg')

访问它

答案 2 :(得分:0)

我建议使用(来自rake gem) http://rake.rubyforge.org/classes/Rake/FileList.html

答案 3 :(得分:0)

要检查文件是否存在,您可以使用:

if File.exists?("#{Rails.public_path}/img/#{image_number}.jpg")

无论文件系统如何,这都可以使用:

if File.exists?(File.join(Rails.public_path, "img", "#{image_number}.jpg"))

要获取所有现有文件,您可以链接#map#select

all_images = (1..100).
  map { |i| File.join(Rails.public_path, "img", "#{i}.jpg") }.
  select{ |path| File.exists? path }
相关问题