DEV Community

Cover image for Ruby on Rails: Dark Mode: TLDR
Yaroslav Shmarov
Yaroslav Shmarov

Posted on • Updated on • Originally published at

Ruby on Rails: Dark Mode: TLDR

You don't need to migrate columns, have a current user, or add new stylesheets.

Here's how it works on my website:


Live Demo - try to click yourself!

Here's how to do it:

  • Set a body class and create links to selecting a theme:
# application.html.erb

<body class="<%= cookies[:theme] %>">

  <% if cookies[:theme] == "light" %>
    <%= link_to "go dark", root_path(theme: "dark") %>
  <% else %>
    <%= link_to "go light", root_path(theme: "light") %>
  <% end %>

  <%= yield %>

Enter fullscreen mode Exit fullscreen mode
  • Persist theme in cookies:
# application_controller.rb

before_action :set_theme

def set_theme
  if params[:theme].present?
    theme = params[:theme].to_sym
    # session[:theme] = theme
    cookies[:theme] = theme
    redirect_to(request.referrer || root_path)
Enter fullscreen mode Exit fullscreen mode
  • Update your css file accordingly:
# application.scss

body.light {
  color: black;
  background-color: white;
body.dark {
  color: white;
  background-color: black;
Enter fullscreen mode Exit fullscreen mode

That's it! Now you can customize your css as you like.

Originally posted here

That's it!🤠

Liked this article? Please follow me! It will really motivate me to post more fun stuff!

Top comments (2)

rebelcolony profile image
Kevin Bett

nice one, works well

mimmico profile image

very nice stuff here, I used it on one of my websites and it works good