跳到內容 跳到搜尋

目前屬性

提供執行緒隔離屬性單例的抽象超級類別,會在每個要求前後自動重設。這讓您可以輕鬆讓整個系統使用每個要求的屬性。

以下是類似完整應用程式的範例,展示如何使用 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 中的屬性應該或多或少用於所有要求的所有動作中。如果您開始在其中放入控制器特定的屬性,就會製造混亂。

方法
A
B
I
N
R
S
包含的模組

屬性

[RW] attributes

類別公開方法

after_reset(*methods, &block)

别名: resets

attribute(*names, default: NOT_SET)

宣告一個或多個屬性,這些屬性都會提供類別和實例存取方法。

選項

  • :default - 屬性的預設值。如果值

是一個程序或 lambda,每當建立實例時就會呼叫它。否則,該值會使用 #dup 複製。在重設屬性時會重新指定預設值。

# File activesupport/lib/active_support/current_attributes.rb, line 114
def attribute(*names, default: NOT_SET)
  invalid_attribute_names = names.map(&:to_sym) & INVALID_ATTRIBUTE_NAMES
  if invalid_attribute_names.any?
    raise ArgumentError, "Restricted attribute names: #{invalid_attribute_names.join(", ")}"
  end

  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

  Delegation.generate(singleton_class, names, to: :instance, nilable: false, signature: "")
  Delegation.generate(singleton_class, names.map { |n| "#{n}=" }, to: :instance, nilable: false, signature: "value")

  self.defaults = defaults.merge(names.index_with { default })
end

before_reset(*methods, &block)

在實例呼叫 reset 之前呼叫這個 callback。用於重設仰賴目前值的外部合作者。

# File activesupport/lib/active_support/current_attributes.rb, line 144
def before_reset(*methods, &block)
  set_callback :reset, :before, *methods, &block
end

instance()

傳回此類別在這個執行緒中的單例實例。如果沒有,就建立一個。

# File activesupport/lib/active_support/current_attributes.rb, line 102
def instance
  current_instances[current_instances_key] ||= new
end

new()

# File activesupport/lib/active_support/current_attributes.rb, line 199
def initialize
  @attributes = resolve_defaults
end

resets(*methods, &block)

reset 於執行個體上呼叫後呼叫此回調。用於重設外部共同作業者,例如 Time.zone

別名為:after_reset
# File activesupport/lib/active_support/current_attributes.rb, line 149
def resets(*methods, &block)
  set_callback :reset, :after, *methods, &block
end

執行個體公開的方法

reset()

重設所有屬性。應在動作前後呼叫,用為依請求的單一 экземпляр時使用。

# File activesupport/lib/active_support/current_attributes.rb, line 218
def reset
  run_callbacks :reset do
    self.attributes = resolve_defaults
  end
end

set(attributes, &block)

在區塊中公開一個或多個屬性。舊值會在區塊結束後傳回。範例說明在請求週期外設定目前屬性的常見用法

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
# File activesupport/lib/active_support/current_attributes.rb, line 213
def set(attributes, &block)
  with(**attributes, &block)
end