класс ActiveSupport::CurrentAttributes
Абстрактный базовый класс, предоставляющий сингултон атрибутов, изолированных по потокам, который автоматически сбрасывается перед и после каждого запроса. Это позволяет легко сделать все атрибуты, относящиеся к запросу, доступными для всей системы.
Следующий пример, аналогичный приложению, демонстрирует, как использовать класс Current для легкого доступа к глобальным атрибутам, относящимся к запросу, без их глубокой передачи повсюду:
# 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
Обратите внимание: легко переусердствовать с глобальным сингултоном, таким как Current, и в итоге запутать вашу модель. Current следует использовать только для нескольких основных глобальных переменных, таких как данные о счете, пользователе и запросе. Атрибуты, хранящиеся в Current, должны использоваться в подавляющем большинстве действий на всех запросах. Если вы начинаете добавлять в него контроллер-специфичные атрибуты, вы создадите путаницу.
Атрибуты
Публичные методы класса
# File activesupport/lib/active_support/current_attributes.rb, line 100
def attribute(*names)
ActiveSupport::CodeGenerator.batch(generated_attribute_methods, __FILE__, __LINE__) do |owner|
names.each do |name|
owner.define_cached_method(name, namespace: :current_attributes) do |batch|
batch <<
"def #{name}" <<
"attributes[:#{name}]" <<
"end"
end
owner.define_cached_method("#{name}=", namespace: :current_attributes) do |batch|
batch <<
"def #{name}=(value)" <<
"attributes[:#{name}] = value" <<
"end"
end
end
end
ActiveSupport::CodeGenerator.batch(singleton_class, __FILE__, __LINE__) do |owner|
names.each do |name|
owner.define_cached_method(name, namespace: :current_attributes_delegation) do |batch|
batch <<
"def #{name}" <<
"instance.#{name}" <<
"end"
end
owner.define_cached_method("#{name}=", namespace: :current_attributes_delegation) do |batch|
batch <<
"def #{name}=(value)" <<
"instance.#{name} = value" <<
"end"
end
end
end
end Объявляет один или несколько атрибутов, для которых будут созданы методы доступа как для класса, так и для экземпляра.
# File activesupport/lib/active_support/current_attributes.rb, line 137 def before_reset(&block) set_callback :reset, :before, &block end
Вызывает этот блок перед вызовом reset для экземпляра. Используется для сброса внешних коллабораторов, зависящих от текущих значений.
# File activesupport/lib/active_support/current_attributes.rb, line 95 def instance current_instances[current_instances_key] ||= new end
Возвращает экземпляр сингултона для этого класса в данном потоке. Если он не существует, создаётся новый.
# File activesupport/lib/active_support/current_attributes.rb, line 188
def initialize
@attributes = {}
end # File activesupport/lib/active_support/current_attributes.rb, line 142 def resets(&block) set_callback :reset, :after, &block end
Вызывает этот блок после вызова reset для экземпляра. Используется для сброса внешних коллабораторов, таких как Time.zone.
Публичные методы экземпляра
# File activesupport/lib/active_support/current_attributes.rb, line 211
def reset
run_callbacks :reset do
self.attributes = {}
end
end Сбрасывает все атрибуты. Следует вызывать перед и после действий, когда используется в качестве сингултона для каждого запроса.
# File activesupport/lib/active_support/current_attributes.rb, line 202 def set(set_attributes) old_attributes = compute_attributes(set_attributes.keys) assign_attributes(set_attributes) yield ensure assign_attributes(old_attributes) end
Отображает один или несколько атрибутов в блоке. Старые значения возвращаются после завершения блока. Пример, демонстрирующий общее использование необходимости установки атрибутов Current вне цикла запроса:
class Chat::PublicationJob < ApplicationJob
def perform(attributes, room_number, creator)
Current.set(person: creator) do
Chat::Publisher.publish(attributes: attributes, room_number: room_number)
end
end
end
© 2004–2021 David Heinemeier Hansson
Licensed under the MIT License.