Reputation: 95
In my application I show a selection of images on the home page. These images are all the same size and are named new1.jpg - new17.jpg and are stored in /public/images/rotate
I'm using some code found online to display a random selection of the images. This is what I'm using:
def random_image
image_files = %w( .jpg .gif .png )
files = Dir.entries(
"#{Rails.root}/public/images/rotate"
).delete_if { |x| !image_files.index(x[-4,4]) }
files[rand(files.length)]
end
And then in my partial:
<img src="/images/rotate/<%= random_image %>"/>
This works perfectly running locally on my mac with rails server, when I push code up to my server on the web half of the images load, and the other half (number seems to change) display a broken image.
When viewing the source code, all images that work are looking at /public/images/rotate/new1.jpg
etc, all the broken images are looking at /public/images/rotate/._new10.jpg
etc
They all have a '._'
before the file name.
Can anyone please shed any light on this for me?
Many thanks
Lee
Upvotes: 1
Views: 165
Reputation: 95
Ended up creating some code that deletes all of the hidden files beginning with ._ from the directory. Then it only outputs the correct images.
Upvotes: 0
Reputation:
Try like this:
def random_image
File.basename(Dir["#{Rails.root}/public/images/rotate/*.{png,gif,jpg}"].sample)
end
Since Dir
takes a glob, *
will match all files, but excludes dotfiles. Then you can ask for any allowed extension. See here: http://ruby-doc.org/core-2.0/Dir.html#method-c-glob
Upvotes: 1