Dynamically Compile Stylesheets with Rails and Sass
Table of content
One of my recent challenges was to give every user a custom stylesheet they can generate to style their own page. This post shows how I did it: how to compile stylesheets with Rails and Sass at runtime, one file per user, and which hidden pitfalls I hit on the way, the biggest being asset caching in production.
Basic Setup
First, we need a basic test app before we get to the interesting part. I am using Rails version 4.2.4. I have already created a User model with a relation to a Style model, which manages the custom CSS for each user.
All values are saved in the database. Our Style table looks like this:
create_table "styles", force: :cascade do |t| t.integer "user_id", null: false t.string "background_color" t.string "block_height" t.string "name_color" t.string "name_style" t.string "name_size" t.string "text_color" t.string "text_style" t.string "text_size" t.string "email_color" t.string "email_style" t.string "email_size" t.datetime "created_at", null: false t.datetime "updated_at", null: false end
We also need a user who owns the custom stylesheet. Our User table looks like this:
create_table "users", force: :cascade do |t| t.string "first_name", null: false t.string "last_name", null: false t.string "email", null: false t.text "text" t.datetime "created_at", null: false t.datetime "updated_at", null: false end
That is enough for this example app: it gives us a handful of styling options to edit. After generating the two models, user and style, we add two gems:
gem 'carrierwave', '~> 0.10.0'
for uploading the logo file, and
gem 'mini_magick', '~> 4.3', '>= 4.3.6'
for image processing. Once the test app is bundled, we generate an uploader for the logos:
rails generate uploader Logo
The models need only small changes. The user model can own many styles:
class User < ActiveRecord::Base has_many :styles end
The style model belongs to a user and mounts the logo uploader from carrierwave:
class Style < ActiveRecord::Base mount_uploader :logo, LogoUploader belongs_to :user end
The basic side of the test app is almost done. A few changes to the Uploader we just generated, and we get to the good part.
In LogoUploader we set store_dir first. Users may upload only images, so the allowed file extensions go into extension_white_list. Then we define two versions: thumb shows the saved logo in the form, and normal is the large image for the index page.
Don't forget to include CarrierWave::MiniMagick otherwise the image resizing will not work.
class LogoUploader < CarrierWave::Uploader::Base include CarrierWave::MiniMagick storage :file def store_dir "uploads/#{model.class.to_s.underscore}/ #{mounted_as}/#{model.id}" end def extension_white_list %w(jpg jpeg gif png) end version :thumb do process :resize_to_fit => [100, 100] end version :normal do process :resize_to_fit => [300, 300] end end
And finally, for the basic setup part for this post, let's have a look at ourcontroller. For ourindexaction we don't need to add anything. Oureditaction is nothing extraordinary, just finding thestylefor the current user, so we would know what to edit. And then there is ourupdateaction, as you can see below, there is nothing strange, except for two lines where I create a new objectGenerateCustomStyle.new(@style.id)and after that I am callingcompileon it. We will get to this in the next section of this post.
class StylesController < ApplicationController def index end def edit @style ||= current_user.styles.find(params[:id]) end def update @style = current_user.styles.new(style_params) if @style.save generate_stylesheet = GenerateCustomStyle.new(@style.id) generate_stylesheet.compile redirect_to root_path else render :edit end end private def style_params params.require(:style) .permit(:background_color, :block_height, :name_color, :name_style, :name_size, :text_color, :text_style, :text_size, :email_color, :email_style, :email_size, :logo) end end
That completes the basic part of the sample App.
Now, the Interesting Stuff
In the lib folder I created generate_custom_style.rb, which handles all the css file work.
The controller calls this class once the new stylesheet params are saved. It needs only the style_id, which it uses to look up what the user saved in the database.
The class sets up its state first:
attr_reader :custom_style, :body, :env, :filename, :scss_file def initialize(style_id) @custom_style = Style.find(style_id) @filename = "#{custom_style.user_id}_#{custom_style.updated_at.to_i}" @scss_file = File.new(scss_file_path, 'w') @body = ERB.new(File.read(template_file_path)).result(binding) @env = Rails.application.assets end
We initialize five things before calling the compile method.
1) The User Style we just saved to the database. Finding it takes one call: Style.find(style_id).
2) A filename. I use user_id + timestamp. The timestamp is optional and everything works without it, but it leaves room to store several styles per user later, so people could switch between them.
3) An scss file. Its path comes from the scss_file_path method:
def scss_file_path @scss_file_path ||= File.join(scss_tmpfile_path, "#{filename}.scss") end
It builds the path to a temporary scss file. A second method makes sure the folder for temporary files exists:
def scss_tmpfile_path @scss_file_path ||= File.join(Rails.root, 'tmp', 'generate_css') unless File.exists?(@scss_file_path) FileUtils.mkdir_p(@scss_file_path) end @scss_file_path end
It looks for a generate_css folder inside tmp and creates it if it is missing.
4) A body to write into the user stylesheet file. The template_file_path method returns the path to the template file that holds it:
def template_file_path @template_file_path ||= File.join(Rails.root, 'app', 'assets', 'stylesheets', '_template.scss.erb') end
The template is a Rails SCSS partial with ERB tags that fill in the saved values. Validate those values when the style is saved (a color code, a size from a fixed list), because a crafted value could otherwise close a rule and inject CSS of its own. The template defines all the variables we need:
$background_color : <%= custom_style.background_color %>; $block_height : <%= custom_style.block_height %>; $name_color : <%= custom_style.name_color %>; $name_style : <%= custom_style.name_style %>; $name_size : <%= custom_style.name_size %>; $text_color : <%= custom_style.text_color %>; $text_style : <%= custom_style.text_style %>; $text_size : <%= custom_style.text_size %>; $email_color : <%= custom_style.email_color %>; $email_style : <%= custom_style.email_style %>; $email_size : <%= custom_style.email_size %>; <% custom_style.logo.recreate_versions! if custom_style.logo.present? %> $logo_url : '<%= custom_style.logo.normal.url %>'; .logo-placeholder{ @if $logo_url !='' { background-image: url($logo_url); } } @import "application";
5) Finally, the Sprockets environment, Rails.application.assets.
Now we can run the compile method.
def compile find_or_create_scss begin scss_file.write generate_css scss_file.flush custom_style.update(css: scss_file) ensure scss_file.close File.delete(scss_file) end end
It first finds or creates our scss file
def create_scss File.open(scss_file_path, 'w') { |f| f.write(body) } end
and writes the body into it.
Next, we generate the css file with scss_file.write generate_css. This is the step that gives each user a different layout.
def generate_css Sass::Engine.new(asset_source, { syntax: :scss, cache: false, read_cache: false, style: :compressed }).render end
Sass gets its source from the asset pipeline, so the file has to be found there first, or it cannot be compiled:
def asset_source if env.find_asset(filename) env.find_asset(filename).source else uri = Sprockets::URIUtils.build_asset_uri(scss_file.path, type: "text/css") asset = Sprockets::UnloadedAsset.new(uri, env) env.load(asset.uri).source end end
This method needs a closer look. Locally, everything works with just
env.find_asset(filename).source
and the css file compiles without problems. The trouble started when I deployed to the server. Rails caches assets in production, which is normal, but the cache knew nothing about our freshly written file. Here is the fix:
uri = Sprockets::URIUtils.build_asset_uri(scss_file.path, type: "text/css") asset = Sprockets::UnloadedAsset.new(uri, env) env.load(asset.uri).source
The ‘scss’ file was missing from env because of Rails cached assets. So the code builds the asset URI for the file itself and loads it through Sprockets directly.
Now we only need to finish what we started.
To make the file appear immediately, we ‘flush’ it:
scss_file.flush
save it to the model
custom_style.update(css: scss_file)
and finally close and delete the temporary scss file:
scss_file.close File.delete(scss_file)
After the redirect to the index action, the changes show up immediately, and the same code works in production mode.
Rails and Sass in 2026: What Has Changed Since 2015
The tutorial above is a record of how this worked in 2015. Almost every tool under it has changed since.
In 2015, sass-rails, the official Rails Sass integration, compiled SCSS with Ruby Sass, the original Ruby implementation that also provides the Sass::Engine class used above. Ruby Sass reached end of life in April 2019. Version 6.0 of sass-rails, released in August 2019, only wraps sassc-rails, and it is still the latest release of the gem.
LibSass, the engine behind sassc and sassc-rails, was deprecated in October 2020 and reached end of life in October 2025. Dart Sass is now the primary implementation. In a Rails app it comes through dartsass-rails, which runs the Dart Sass executable as part of assets:precompile, or through cssbundling-rails if the app already uses Node.js. Dart Sass 1.80 also deprecated @import, which our template uses, in favor of @use.
The pipeline changed too. From Rails 8 onwards, new apps use Propshaft instead of Sprockets, and Propshaft does not transpile Sass at all. Even on Sprockets, current sprockets-rails sets Rails.application.assets to nil when config.assets.compile is off, and that is the setting Rails generates for production.
For per-user stylesheets today, two routes fit better. If you still need Sass at runtime, the sass-embedded gem compiles a string directly with Sass.compile_string, with no asset pipeline involved. Simpler still, compile one stylesheet at deploy time and write each user’s saved colors and sizes into CSS custom properties. The browser applies them, and no per-user file has to be compiled or cleaned up.
Final Thoughts
I usually work on the backend rather than the frontend, but getting this to work properly was an interesting task. I hope it saves someone else time.
The full test app is on Git; the repository is now archived and read-only.
At the time, my colleague and I were also working on a small gem for this functionality.
Our Ruby developers work in a team of 80+ senior engineers, and you can read more about the company on our About Us page.