How I implemented CSS Modules to Ruby on Rails, easily.

Fatih Kadir Akın
4 min readMay 28, 2016

Front-end has grown up. It is not easy to maintain front-end projects as we were doing in 2000’s. There are so many technologies, so many techniques and paradigms. Front-end is more responsible part of an application now. And when you develop a front-end included project, it may become hard to manage.

Smart people realise this issues and try to make the front-end more modular and more maintainable. One of these attempts is CSS Modules approach. This basically aims to separate CSS management into modules (as we are doing in JavaScript for a while).

Me and Adem are working in a Rails based project and it become slightly confusing b/c of the CSS parts. For sure, we are separating CSS files into files to make it manageable, but it’s not too easy to maintain HTML side then.

Modular and reusable CSS! — No more conflicts. — Explicit dependencies. — No global scope. (from CSS Modules)

I tried to find a cool way to integrate CSS Modules into our Rails project, but I cannot. So I decided to make my own.

Rails has awesome features that I still surprise when I learn about them. When I learn about I can write my own Sprockets Processors it made me feel powerful👌🏻

Me when I learn about Sprockets’ asset processors.

I created a file: config/initializers/css_modules.rb to write my own processor.

Sprockets.register_postprocessor "text/css", CSSModules.new

This allows you to register your own postprocessor (I want SASS to compile first)

And I created a class into the css_modules.rb

class CSSModules
def call(input)
{data: "body {background-color: red}"}
end
end

This rewrote all of my CSS files with body {background-color: red} (Yes, a bit trolling)

Now I need a thing that parses CSS, so I can rebuild my CSS files modularised. I found css_parser gem to parse my CSS files.

My development of config/initializers/css_modules.rb come this:

--

--