ruby 82 lines · 4 tabs

Memoizing Computed User Permissions Per Request with Current Attributes in Rails

Shared by codesnips Aug 2026
4 tabs
class Current < ActiveSupport::CurrentAttributes
  attribute :user, :request_id

  def permissions
    @permissions ||= PermissionSet.new(user)
  end

  def reset
    super
    @permissions = nil
  end
end
4 files · ruby Explain with highlit

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

ruby
class CommentsController < ApplicationController
  before_action :set_post

  def create
    @comment = @post.comments.build(comment_params)

System test: asserting Turbo Stream responses

rails hotwire turbo
by codesnips 4 tabs
ruby
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

rails activerecord patterns
by Alex Kumar 1 tab
ruby
module Api
  module V1
    class UsersController < BaseController
      def show
        user = User.includes(:profile).find(params[:id])

ETags for conditional requests and caching

rails caching http-caching
by Alex Kumar 1 tab
ruby
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

rails turbo hotwire
by codesnips 4 tabs
ruby
require "csv"

class PeopleCsvStream
  include Enumerable

  HEADERS = %w[id full_name email signed_up_at plan].freeze

Resilient CSV Export as a Streamed Response

rails performance streaming
by codesnips 3 tabs
erb
<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)

rails hotwire stimulus
by Henry Kim 2 tabs

Share this code

Here's the card — post it anywhere.

Memoizing Computed User Permissions Per Request with Current Attributes in Rails — share card
Link copied