Fork me on GitHub
Hoopla! - now with extra whiz-bang home

Including stylesheets conditionally turned out to be a fairly easy task. I'll outline the solution here using extractions from my code:

<typo:code lang="ruby"> class ApplicationController < ActionController::Base

attr_accessor :stylesheets before_filter {|c| c.stylesheets ||= []; c.stylesheets << c.class.name.sub('Controller','').downcase }

end This adds an instance var @stylesheets that starts as an array. It is given, by default the name of the currently active controller. note: this prints the derived class's name, not 'application'.

This means that you can now add stylesheets to the soon-to-be-rendered view anywhere in your code you want.

<typo:code lang="ruby"> class UsersController < ApplicationController # if you have a stylesheet that governs just one action def show

stylesheets << 'users_show'

end end

And it's surprisingly simple to output the required code to the browser. Just add one line to your app/views/layouts/application.rhtml file:

<typo:code lang="rhtml"> <%= stylesheet_link_tag 'application', :media => 'all' %> <%= stylesheet_link_tag 'structure'', :media => 'all' %> <%= stylesheet_link_tag 'fonts'', :media => 'all' %> <%= stylesheet_link_tag 'forms', :media => 'all' %> <%= stylesheet_link_tag 'colors', :media => 'all' %> <%= @stylesheets.collect { |file| stylesheet_link_tag file }.join("\n") if @stylesheets %> <%= javascript_include_tag :defaults %>

This is so simple that there's no real point in turning it into a plugin but if anybody wants it that way just let me know.

Update: The version I ended up using in my app did some testing for the existence of the file before it included it as a stylesheet. I decided it was more important to avoid the 404 errors (especially the way they cruft up the logfile) than it was to have the app disk-optimized. So here's my new application_controller:

<typo:code lang="ruby"> class ApplicationController < ActionController::Base

attr_accessor :stylesheets before_filter do |c|

c.stylesheets ||= []
klass = c.class.name.sub('Controller','').downcase
c.stylesheets << klass if File.exists?("#{RAILS_ROOT}/public/stylesheets/#{klass}.css")

end

end

blog comments powered by Disqus