user1608920
user1608920

Reputation: 157

How to access public folder from a model method?

I want to do something like this in the model, using public folder like a 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

Is there any way for Rails to "see" files in public directory this way ?

Upvotes: 4

Views: 3433

Answers (4)

wacko
wacko

Reputation: 3434

For checking if a file exist, you can use:

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

And this will work regardless of the file system:

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

To get all the existing files, you can chain #map and #select

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

Upvotes: 0

Beat Richartz
Beat Richartz

Reputation: 9622

If you use the asset pipeline and you want to check whether an asset exists, look for it in the asset folder:

 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

If you have the asset in the public folder, which is not recommended (for various reasons) unless you use Rails < 3 and / or built some asset management extension yourself, you can look for it there:

 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

Upvotes: 5

Igor Kasyanchuk
Igor Kasyanchuk

Reputation: 774

I suggest to use (from rake gem) http://rake.rubyforge.org/classes/Rake/FileList.html

Upvotes: 0

nurettin
nurettin

Reputation: 11756

You can access it with Rails.root.join('public', 'img', '1.jpg')

Upvotes: 0

Related Questions