Logo

Edward Ford

  • Archive
  • RSS
  • Ask me anything

CSS files for Rails Controllers

Whilst working on various different projects using CSS frameworks such as SASS, 960 Grid System and Blueprint I have found overriding with specific files per controller to be a much cleaner process. 

Note: I think Rails 3.1 actually does this out of the box

Obviously it is not always necessary to create a new css file for every controller so I needed a way to include the file if it exists.  This saves on unwanted entries in log files for file cannot be found when we kind of know that already.

So what I did was add a before filter to the application controller.

class ApplicationController < ActionController::Base

…

before_filter :controller_styles

private

  def controller_styles

    @all_styles = Array.new
    @all_styles = [“reset”, “960”, “layout”, “nav”, “text”]

    controller_style = File.join(Rails.root, “public/stylesheets/”, “#{request.parameters[:controller]}.css”)
    if File.exist?(controller_style)
      @all_styles.push(request.parameters[:controller].to_s)
    end

  end

end

What this simple code does is call the method at the start of every request.  The method then creates an array with the default css files already included. 

A lookup is then made in the stylesheet directory for a css file with the same name as the requesting controller.  If it exists, push it on to the end of the array.  If it doesn’t, don’t.

Then in the main layout.html.erb view file, include:

<%= stylesheet_link_tag @all_styles %>

into the head of the html and you have the option to override your CSS in a clean structured manor.

Simples!

    • #rails
    • #css
  • 8 months ago
  • 8
  • Comments
  • Permalink
  • Share
    Tweet

8 Notes/ Hide

  1. edwardford posted this

Recent comments

Blog comments powered by Disqus
← Previous • Next →

Edward Ford

About

Freelance Digital Marketing Consultant & Web Developer venturing around the world on route to San Francisco.

See my portfolio site

Me, Elsewhere

  • @edward_ford on Twitter
  • My Skype Info
  • Linkedin Profile

Twitter

loading tweets…

Following

I Dig These Posts

See more →
  • Post via aslakhellesoy
    Cucumber 1.0.0

    Cucumber

    I am so thrilled about this I set up a blog!

    Today I released Cucumber 1.0.0 after three years in the making. Here are...

    Post via aslakhellesoy
  • Photo via theartofanimation

    Yun Byoung Chul PENE MENN

    Photo via theartofanimation
  • RSS
  • Random
  • Archive
  • Ask me anything
  • Mobile

Effector Theme by Carlo Franco.

Powered by Tumblr