class Current < ActiveSupport::CurrentAttributes
attribute :user, :request_id
def permissions
@permissions ||= PermissionSet.new(user)
end
def reset
super
@permissions = nil
end
end
class PermissionSet
def initialize(user)
@user = user
end
def allow?(permission)
computed.include?(permission.to_s)
end
private
def computed
@computed ||= begin
return Set.new if @user.nil?
granted = Set.new
@user.roles.includes(:grants).each do |role|
role.grants.each { |g| granted << g.permission }
end
FeatureFlag.enabled_for(@user).each do |flag|
granted << "feature:#{flag.key}"
end
granted << "admin:*" if @user.admin?
granted
end
end
end
class ApplicationController < ActionController::Base
before_action :set_current_user
private
def set_current_user
Current.user = User.find_by(id: session[:user_id])
end
def authorized?(permission)
Current.permissions.allow?(permission)
end
def authorize!(permission)
return if authorized?(permission)
raise ActionController::RoutingError, "Not authorized"
end
end
class User < ApplicationRecord
has_many :memberships
has_many :roles, through: :memberships
def can?(permission)
# Reuse the per-request memoized set when this is the current user,
# otherwise compute a throwaway set for the given user.
if Current.user == self
Current.permissions.allow?(permission)
else
PermissionSet.new(self).allow?(permission)
end
end
def admin?
role_names.include?("admin")
end
def role_names
roles.pluck(:name)
end
end
Authorization checks often recompute the same permission set many times within a single request: a controller filter, a view helper, and a serializer might each ask "can this user edit posts?" independently. Recomputing that from roles, feature flags, and group memberships on every call adds redundant database work. This snippet caches the computed permission set once per request using Rails' ActiveSupport::CurrentAttributes, which provides thread-isolated, per-request state that Rails automatically resets between requests.
In Current attributes, the class holds a user and a lazily built permissions object. The permissions method memoizes with ||=, so the first call constructs a PermissionSet for Current.user and every subsequent call in the same request returns the same instance. Because CurrentAttributes is reset after each request by Rails' executor, there is no risk of a stale permission set leaking into the next request or bleeding across threads.
The PermissionSet service does the actual expensive work exactly once. Its computed method loads roles and flag data and folds them into a Set of permission strings, wrapped in @computed ||= so the aggregation runs a single time even though the object may be queried repeatedly. allow? becomes a cheap Set membership test after that. Keeping this logic in a plain service object rather than the model keeps the query fan-out in one place and makes it easy to test in isolation.
In ApplicationController, a before_action assigns Current.user from the session, establishing the identity that Current.permissions depends on. The authorize! helper and authorized? predicate both read through Current.permissions, so the whole request shares one computation. Delegating the model's can? through Current (shown in User model) means even view and serializer code benefits without threading the controller state around.
The main trade-off is coupling to global-ish request state, so this pattern suits read-mostly permission checks, not per-record authorization that varies by argument. A subtle pitfall is background jobs: Current is not automatically populated there, so jobs must set Current.user explicitly. When permission checks dominate a hot path, this memoization removes duplicate queries with almost no new machinery.
Related snips
class CommentsController < ApplicationController
before_action :set_post
def create
@comment = @post.comments.build(comment_params)
System test: asserting Turbo Stream responses
class Post < ApplicationRecord
belongs_to :author, class_name: 'User'
has_many :comments, dependent: :destroy
scope :published, -> { where.not(published_at: nil).where('published_at <= ?', Time.current) }
scope :draft, -> { where(published_at: nil) }
ActiveRecord scopes for reusable query logic
module Api
module V1
class UsersController < BaseController
def show
user = User.includes(:profile).find(params[:id])
ETags for conditional requests and caching
class PostsController < ApplicationController
def index
@posts = Post.includes(:author)
.order(created_at: :desc)
.page(params[:page])
.per(10)
Turbo Frames: infinite scroll with lazy-loading frame
require "csv"
class PeopleCsvStream
include Enumerable
HEADERS = %w[id full_name email signed_up_at plan].freeze
Resilient CSV Export as a Streamed Response
<form data-controller="query-sync" data-action="change->query-sync#apply">
<select name="status" class="rounded border p-2">
<option value="">Any</option>
<option value="open">Open</option>
<option value="closed">Closed</option>
</select>
Filter UI that syncs query params via Stimulus (no front-end router)
Share this code
Here's the card — post it anywhere.