класс 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 96
def attribute(*names)
generated_attribute_methods.module_eval do
names.each do |name|
define_method(name) do
attributes[name.to_sym]
end
define_method("#{name}=") do |attribute|
attributes[name.to_sym] = attribute
end
end
end
names.each do |name|
define_singleton_method(name) do
instance.public_send(name)
end
define_singleton_method("#{name}=") do |attribute|
instance.public_send("#{name}=", attribute)
end
end
end Объявляет один или несколько атрибутов, которым будут предоставлены методы доступа как для класса, так и для экземпляра.
# File activesupport/lib/active_support/current_attributes.rb, line 91 def instance current_instances[name] ||= new end
Возвращает синглтон экземпляр для этого класса в этом потоке. Если его нет, создается новый.
# File activesupport/lib/active_support/current_attributes.rb, line 157
def initialize
@attributes = {}
end Публичные методы экземпляра
# File activesupport/lib/active_support/current_attributes.rb, line 180
def reset
run_callbacks :reset do
self.attributes = {}
end
end Сбрасывает все атрибуты. Следует вызывать перед и после действий, когда используется в качестве синглтона на уровне запроса.
# File activesupport/lib/active_support/current_attributes.rb, line 171 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–2018 David Heinemeier Hansson
Licensed under the MIT License.