Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 690
user1608920 Avatar asked Oct 22 '25 09:10

user1608920


1 Answers

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
like image 190
Beat Richartz Avatar answered Oct 23 '25 23:10

Beat Richartz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!