DEV Community

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

Posted on • Edited on • Originally published at blog.corsego.com

7 2

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:

dark-mode

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 %>

</body>
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)
  end
end
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!

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (2)

Collapse
 
rebelcolony profile image
Kevin Bett

nice one, works well

Collapse
 
mimmico profile image
mimmo

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

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs