ruby
26 lines · 6 steps
Idle session timeout in a Rails controller
A before_action logs the last-seen time on every request and signs users out after 30 minutes of inactivity.
Explained by
highlit
1class ApplicationController < ActionController::Base
2 INACTIVITY_TIMEOUT = 30.minutes
3
4 before_action :expire_stale_session
5
6 private
7
8 def expire_stale_session
9 return unless current_user
10
11 last_seen = session[:last_seen_at]
12
13 if last_seen && Time.zone.parse(last_seen) < INACTIVITY_TIMEOUT.ago
14 reset_session
15 redirect_to new_session_path, alert: "Your session expired due to inactivity."
16 return
17 end
18
19 session[:last_seen_at] = Time.current.iso8601
20 end
21
22 def current_user
23 @current_user ||= User.find_by(id: session[:user_id])
24 end
25 helper_method :current_user
26end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A sliding-window timeout works by rewriting the last-seen timestamp on every authenticated request.
- 2Storing timestamps as ISO8601 strings in the session keeps them serializable and unambiguous across time zones.
- 3reset_session clears the session server-side, so an expired user must sign in again before continuing.
Related explainers
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
ruby
class WeeklySignupsReport DEFAULT_WEEKS = 12 def initialize(weeks: DEFAULT_WEEKS, source: User.all)
Building a weekly signups report in Rails
service object
aggregation
group by
Intermediate
7 steps
ruby
class ApplicationController < ActionController::Base EXPERIMENTS = { checkout_button_color: %w[control blue green], onboarding_flow: %w[control streamlined]
How A/B test cohorts are assigned in Rails
a-b-testing
cookies
hashing
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/idle-session-timeout-in-a-rails-controller-explained-ruby-c64a/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.