Question: ```
html{ 
    background: url(/assets/flower.jpg) no-repeat center center fixed; 
    -webkit-background-size: cover;   
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

```

How can I make this code randomly choose from a selected number of pictures as background. I am using Rails 3, so have that in mind, if that will simplify the process of making this work.
THANKS! :D

Answer: 
The easiest way is to create an actions with redirect to a random image the browser will follow the redirect.

app/controller/background\_controller.rb

```
class BackgroundController < ApplicationController
  def image
    redirect_to "/assets/images/background_#{rand(10)}.jpg"
  end
end

```

This will randomly redirect to a background image between `background_0.jpg` and `background_9.jpg`

config/routes.rb

```
Something::Application.routes.draw do
  …
  get '/random_background.jpg', to: 'background#image'
  …
end

```

css

```
html{ 
  background: url(/random_background.jpg) no-repeat center center fixed;
}

```

---

Some more advanced would be to do something like this in a Middleware, so such a request won't need so whole rails stack.

app/middleware/random\_background\_middleware.rb

```
class RandomBackgroundMiddleware
  def initialize(app, count = 10)
    @app = app
    @count = count
  end

  def call(env)
    if env["PATH_INFO"] == "/random_background.jpg"
      [302, {"Location" => "/assets/images/background_#{rand(@count)}.jpg")}, '']
    else
      @app.call(env)
    end
  end
end

```

`config/application.rb`

```
config.middleware.insert_before 0, "RandomBackgroundMiddlware"

```

`insert_before 0` is used to place it at the top of the Middleware-Chain

---

Or even better would be something like this in your webserver config. But I don't how or if this can be done.
I did this by creating a random class name in the view like this:

```
<div class="homepage-banner-<%= rand(1..10) %>">

```

Then I just added multiple images to my css like this:

```
.homepage-banner-1
  background-image: image-url('homepage/homepage-feature-1.jpg')

.homepage-banner-2
  background-image: image-url('homepage/homepage-feature-2.jpg')

.homepage-banner-3
  background-image: image-url('homepage/homepage-feature-3.jpg')

etc.

```

Not sure if that's the best way, but it's very simple.