Reputation: 1335
I am working on a Rails 3.1 app and am happily using SASS and CoffeeScript. I particularly like the SASS extensions of variables and imports. I have constructed a single _global-settings.css.scss file which contains ALL of the hex constant values I use throughout all of my stylesheets. This gives me a single place to manage colors, fonts and layout dimensions. Very DRY.
But, if I wish to use JQuery to tweak my css dynamically, I no longer have access to my css compile-time variables, and must reproduce the same data as a JSON hash in a .js.coffee file. Not DRY at all.
Here is my question: Before I go off and build a rake task to munge my css settings file into an equivalent CoffeeScript hash, does anyone have a more clever idea? Like hiding all the values in a hidden div in an html file?
Upvotes: 1
Views: 1664
Reputation: 434685
You'd have an easier time moving your CSS configuration into Ruby and then sending your _global-settings.css.scss
and a small piece of CoffeeScript through ERB. Then you have your settings in place and you can access them everywhere.
Somewhere in Ruby you'd have this:
CSS_SETTINGS = {
:text_color => '#333',
:text_color_hilite => '#f33',
:font_size => '14px',
#...
}
Then rename your _global-settings.css.scss
to _global-settings.css.scss.erb
and use things like this inside it:
$text-color: '<%= CSS_SETTINGS[:text_color] %>';
// ...
And inside a global_settings.js.coffee.erb
you could have this:
window.app.global_settings = <%= CSS_SETTINGS.to_json.html_safe %>
You could even write a simple view helper that would SASSify a Hash:
def sassify(h)
h.map do |k, v|
# You might want more escaping for k and v in here, this is just
# a simple proof of concept demo.
[ '$', k.to_s.gsub('_', '-'), ': ', "'#{v}'", ';' ].join
end.join("\n")
end
and then you could say this in your _global-settings.css.scss.erb
:
// Import global CSS settings.
<%= sassify(CSS_SETTINGS).html_safe %>
You could also monkey patch a to_sass
into Hash and use CSS_SETTINGS.to_sass
but that's probably taking things one step too far.
Upvotes: 5