Dynamic CSS Image Background in Rails

I'm working on some changes to a Rails application for a client.

Today I needed to change the style of a div from a static image background to a more dynamic image. Specifically, I needed the background (because I needed the text in the div above the image) of the div to be an image that was uploaded to the Rails application via the Paperclip gem, so luckily it was accesible via the .url instance method of Paperclip.

After cracking my head against the wall for a while, I remembered a kind of CSS reference that is hated by almost everyone for obvious reasons (lack of encapsulation, repetition of code), but, it was perfect to dynamically alter a value from Rails, so I came up with this solution:

Previously, with a static background: ```css

#application.css
.styled_div {
    background: url("public/background1.jpg")
    ###... Omitted code
}


#app/views/resource/show.html.haml
###... Omitted code
.styled_div
    content that I
    need above the
    background

And now, with the dynamic background: css

#application.css
.styled_div {
    #   background: url("public/background1.jpg")
    # ... Omitted code
}

#app/views/resource/show.html.haml
###... Omitted code
%div{:class => 'styled_div', :style => %(background:url("#{resource.background.url(:medium)}") no-repeat center)}
    content that I
    need above the
    background

``` And it works perfectly. Sometimes it's useful to be able to be aware of the considered "bad practices" because they can help you get a solution that you wouldn't have thought about if you only know the "good practices".