Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write ruby code in css file

I am having an rails application,in which I need a css file in such a way that its property can be changed by ruby code. ex. background_color :<%= ruby code that return background color %>

So a user can set its css property and will be applicable to only that user like a theme.

Thanks!

like image 931
gsoni Avatar asked Oct 19 '25 18:10

gsoni


2 Answers

You can't/shouldn't do this. You will precompile your assets so there is no way of dynamically adapting to changing variables. It is a bad pattern to use.

A much easier approach is to either add a class .active .inactive on your elements (body). Or output inline css in your head for things like custom colors etc depending on users that are signed in.

What are you trying to do? It sounds like something you'd do to check whether you are in production or development? In which case you could do something like:

<body class='<%= "development" if Rails.env == 'development' %>'>

or even

<body <%= "style='background-color: red;'" if Rails.env == 'development' %>

You should never need to use ruby in your css and javascript, if you find yourself doing it you are probably approaching it in the wrong way. At least that is what I have found after many attempts to do this nicely.

You can do this in your head:

<style>
    .user .name{
       color: <%= current_user.chosen_color %>;
    }
</style>

p.s. data-attributes are a very effective way of passing variables, etc to javascript

p.s.2. this is an adaptation of my answer here: Creating scss variable in config.rb for scss files I think it is relevant for anyone who comes here too, so I answered here too.

like image 150
Mosselman Avatar answered Oct 21 '25 07:10

Mosselman


If you just need something simple, then you could do in your layout:

<head>
....
<% unless current_user.theme.nil? %>
<style>
body{
  background:<%= current_user.theme.background_color%>;
}
</style>
</head>
<% end %>

If you're starting a new project, SASS is the way to go, and probably is the way to go if you have sufficient time. If just a couple of entries, it might not be bad to do it in the HTML.

Note: I feel a little dirty about this, but it'll work.

like image 21
Jesse Wolgamott Avatar answered Oct 21 '25 08:10

Jesse Wolgamott