- 1.0.0
- 1.1.6
- 1.2.6
- 2.0.3
- 2.1.0
- 2.2.1
- 2.3.8
- 3.0.0
- 3.0.9
- 3.1.0
- 3.2.1
- 3.2.8
- 3.2.13
- 4.0.2
- 4.1.8
- 4.2.1
- 4.2.7
- 4.2.9
- 5.0.0.1
- 5.1.7
- 5.2.3 (0)
- 6.0.0 (0)
- 6.1.3.1 (0)
- 6.1.7.7 (0)
- 7.0.0 (0)
- 7.1.3.2 (38)
- 7.1.3.4 (0)
- What's this?
Current Attributes
Abstract super class that provides a thread-isolated attributes singleton, which resets automatically before and after each request. This allows you to keep all the per-request attributes easily available to the whole system.
The following full app-like example demonstrates how to use a Current class to facilitate easy access to the global, per-request attributes without passing them deeply around everywhere:
# app/models/current.rb class Current < ActiveSupport::CurrentAttributes attribute :account, :user attribute :request_id, :user_agent, :ip_address resets { Time.zone = nil } def user=(user) super self.account = user.account Time.zone = user.time_zone end end # app/controllers/concerns/authentication.rb module Authentication extend ActiveSupport::Concern included do before_action :authenticate end private def authenticate if authenticated_user = User.find_by(id: cookies.encrypted[:user_id]) Current.user = authenticated_user else redirect_to new_session_url end end end # app/controllers/concerns/set_current_request_details.rb module SetCurrentRequestDetails extend ActiveSupport::Concern included do before_action do Current.request_id = request.uuid Current.user_agent = request.user_agent Current.ip_address = request.ip end end end class ApplicationController < ActionController::Base include Authentication include SetCurrentRequestDetails end class MessagesController < ApplicationController def create Current.account.messages.create(message_params) end end class Message < ApplicationRecord belongs_to :creator, default: -> { Current.user } after_create { |message| Event.create(record: message) } end class Event < ApplicationRecord before_create do self.request_id = Current.request_id self.user_agent = Current.user_agent self.ip_address = Current.ip_address end end
A word of caution: It’s easy to overdo a global singleton like Current and tangle your model as a result. Current should only be used for a few, top-level globals, like account, user, and request details. The attributes stuck in Current should be used by more or less all actions on all requests. If you start sticking controller-specific attributes in there, you’re going to create a mess.
Constants
INVALID_ATTRIBUTE_NAMES = [:set, :reset, :resets, :instance, :before_reset, :after_reset, :reset_all, :clear_all]
Attributes
[RW] | attributes |