Rails: is it possible to refer to an instance variable (e.g. @ user.color_preferred) with an interpolated string?

I am trying to change the background color with the color_preferred field defined in the User model.

/ * file example.css.scss.erb * /

 $color: <%= @user.color_preferred %>; body { background-color: $color; color: #333; font-family: verdana, arial, helvetica, sans-serif; font-size: 13px; line-height: 18px; } 

Is it possible to access ruby ​​instance variables from sass files? Tk. Rafa.

+4
source share
3 answers

I find this impossible. Sass compiles during deployment (in Rails 3.1), after which it is a static file. That would not make sense either. The css files must be user independent and cached for a long time.

Why don’t you insert the style tag inside your layout and overwrite the default style defined inside your css if the user has chosen the preferred color?

+3
source

Yes. You can do this by expanding Sass :: Script :: Functions . Just create a ruby ​​file, add this bit and load it into a script environment (i.e. / config / initializers /):

 module Sass::Script::Functions def var(name) assert_type name, :String, :name @environment.var(name.value) end declare :var, :args => [:string] end 

Then you can do the following:

 $button-primary-bg: #000; $button-secondary-bg: #123; $button-tertiary-bg: #abc; $button-names: (primary, secondary); @each $name in $names { .button-#{$name} { background: var("button-#{$name}-bg"); } } 
+1
source

It is possible, but it is connected with hacking Sass and deepening into it. The best way, as iGel said, is to create different “themes” and incorporate it into your body depending on the user's preferences.

Say that you have main.css and some colors of the colors (let's say a different background body depending on the user's choice)

  = stylesheet_include_tag 'main' = stylesheet_include_tag "#{@user.color_preferred}" 

then you have ready-made colors like blue.sass, red.sass, green.sass, etc.

they are easy to generate, as you can just use the variable, as in your example, except that you need to reproduce it to support different colors.

0
source

All Articles