jthomas
jthomas

Reputation: 1172

Best way to generate a static CSS file with Rails

I'm a rails newb and I'm creating an app for some practice where I save CSS snippets. Right now, I've got a mvc setup for Entries, where I can do all the typical crud stuff. Give the entry a title, description and a css snippet. I'd like to use the css snippets I've saved in each Entry in the database to create a stylesheet full of all snippets for users to be able to download. Eventually, I would like to provide a CSS, LESS, and SASS version of this stylesheet, so you can just pick your flavor to download. And even further down the road, I would like users to be able to customize which snippets will be in their download of the CSS/Less/Sass version of the file they download, or even a zip of all 3.

The part where I'm getting hung up is the approach of when and how to generate the file(s). For the sake of keeping things simple, I'm fine with just starting with a CSS file, and applying that knowledge to creating Less and Sass versions later, but if you have tips on that as well, that woudl be great.

The answer over at this question gave me some insight into Sass:Engine, but I wasn't able to glean my answer in full from it. Convert SASS to CSS using SASS gem

Upvotes: 2

Views: 815

Answers (1)

Ben Scheirman
Ben Scheirman

Reputation: 40951

With Rails you aren't limited to rendering HTML. You could provide your own view that renders the context as text/css and the file would be displayed by the browser.

If you want to render it inline, you can do this:

def test_css_download
  css = "body { font-family: Arial; }"
  render :text => css, :content_type => "text/css"
end

If you want to have them download it as a file, you can use send_data like this:

def test_css_download
  css = "body { font-family: Arial; }"
  send_data css, :filename => "styles.css", :type => "text/css", :disposition => "attachment"
end

When you visit this route the browser will download the content as a file.

Upvotes: 2

Related Questions