If you are building a Rails app and for the sake of practice try not to use JS, here is a recipe for adding a dark mode to your website using cookies.
Step 1: in the Application Controller set up cookies
We first set cookies and then redirect the user to a page. In our case, if a user is logged in, they will be redirected to their landing page and otherwise, to the welcome screen:
def moon cookies[:moon] = { value: 'dark mode on' } if @logged_in_user redirect_to user_stories_path else redirect_to welcome_index_path end end
Although the light mode is the default one, we also set a method for it so that the user can switch the dark mode off:
def sun cookies.delete(:moon) if @logged_in_user redirect_to story_books_path else redirect_to welcome_index_path end end
Step 2: Create routes
Now, in the
config/routes.rb create routes for these two methods. You’ll need the routes later.
get '/moon', to: 'application#moon', as: 'moon' get '/sun', to: 'application#sun', as: 'sun'
Step 3: Enable page to check cookies
In the
app/views/layouts/application.html.erb, in the
<head> I introduced the following code to first check whether cookies are on, and if so — to load an appropriate stylesheet:
<head> <title> ✨ Fierce Stories ✨ </title> <%= csrf_meta_tags %> <%= csp_meta_tag %> <link rel="icon" href=""> <% if cookies[:moon] %> <%= stylesheet_link_tag 'application_dark', media: 'all', 'data-turbolinks-track': 'reload' %> <% else %> <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %> <% end %> <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %> </head>
Step 4: Add buttons to switch Dark Mode on/off
In our header, we have a Dark Mode/Light Mode button. The code for it looks as following:
<% if cookies[:moon] %> <%= button_to 'Light Mode', sun_path, method: :get%> <% else %> <%= button_to 'Dark Mode', moon_path, method: :get%> <% end %>
note: You need a
method: :get because that’s not what the buttons default to.
Step 5: Create the Dark Stylesheet
In
app/assets/stylesheets duplicate your basic stylesheet and change colors where appropriate.
Photo by Sam Kolder from Pexels
Discussion
Good, however I think students at Yale deserve a better way to set light/dark😉
actionfor
moonand
sun, as well you don't need to use
routesat all for cookies. I would make it shorter:
And for setting backgrounds, you don't need to have a lot of stylesheet files. Just use css variables:
Source: blog.corsego.com/ruby-on-rails-dar...
I think you can combine Rails and dbdesigner.id as your database designer. This can make your project readable and clear documentation.
Thank you for your comment — dbdesigner.id looks interesting. Can you tell me how it relates to what I wrote?
I just give you an information about it. I hope this can helped your work...