Dan Lee
Dan Lee

Reputation: 704

Random image css with attribution

I'm looking to do a random image in ruby on rails in the background via css. The difference being I want to also display a attribution to the person who took the image. I'm only going to have 5 images so don't see the need for a database. I want to keep it low maintenance. What is the best way to extend the following?

<style type="text/css">
  html {
    background: url(<%= randomized_background_image %>) no-repeat center center fixed; 
  }
</style>

Now in your application_helper

def randomized_background_image
  images = ["assets/foo.jpg", "assets/random.jpg", "assets/super_random"]
  images[rand(images.size)]
end

Upvotes: 0

Views: 651

Answers (1)

Alex Moore-Niemi
Alex Moore-Niemi

Reputation: 3372

Well, first a disclaimer, I don't think you should be doing this. Embedding Ruby in CSS is pretty sloppy. Why? It crosses abstraction layers and mixes concerns unnecessarily.

Ruby (and erb templates generally) really don't have a great model of your document object, but guess who does? Jquery! :) So as an alternative, take a look at the $ examples in the answers to this question: Random background images CSS3

That said, to do this in Ruby, the way to do it would be to have a hash object for each of your images then put them in your array, ie:

image_hash = Hash[url: 'http://', attribution: 'Author K. Dude']
=> {:url=>"http://", :attribution=>"Author K. Dude"}
image_hash[:url]
=> "http://"
array_of_image_hashes = Array[image_hash]
=> [{:url=>"http://", :attribution=>"Author K. Dude"}]
array_of_image_hashes.first[:url]
=> "http://"

This way you could share the same local variable (a random index of your array) in your view both at the style level and just as a string in a span underneath it. So, <%= random_image_result[:url] %> in style and <%= random_image_result[:author] %> in a span. I'm guessing you're doing Rails, and if so, I'd recommend putting your generator method in a helper, which is included automatically at the controller level so it is available to your view.

Upvotes: 1

Related Questions