跳至內容 跳至搜尋

Active Model 屬性方法

提供一種方式在您的方法中新增字首和字尾,以及處理類似 ActiveRecord::Base 的類別方法(例如 `table_name`)。

實作 `ActiveModel::AttributeMethods` 的需求是

  • 在您的類別中 `include ActiveModel::AttributeMethods`。

  • 呼叫您想新增的每個方法,例如 `attribute_method_suffix` 或 `attribute_method_prefix`。

  • 在呼叫其他方法後呼叫 `define_attribute_methods`。

  • 定義您已宣告的各種一般性 `_attribute` 方法。

  • 定義 `attributes` 方法,傳回一個雜湊作為結果,其中每個屬性名稱在您的模型中是雜湊鍵,而屬性值是雜湊值。 雜湊 鍵必須是字串。

最小的實作可以是

class Person
  include ActiveModel::AttributeMethods

  attribute_method_affix  prefix: 'reset_', suffix: '_to_default!'
  attribute_method_suffix '_contrived?'
  attribute_method_prefix 'clear_'
  define_attribute_methods :name

  attr_accessor :name

  def attributes
    { 'name' => @name }
  end

  private
    def attribute_contrived?(attr)
      true
    end

    def clear_attribute(attr)
      send("#{attr}=", nil)
    end

    def reset_attribute_to_default!(attr)
      send("#{attr}=", 'Default Name')
    end
end
命名空間
方法
A
M
R

常數

CALL_COMPILABLE_REGEXP = /\A[a-zA-Z_]\w*[!?]?\z/
 
NAME_COMPILABLE_REGEXP = /\A[a-zA-Z_]\w*[!?=]?\z/
 

實例公開方法

attribute_missing(match, ...)

attribute_missing 類似於 method_missing,但用於屬性。當呼叫 method_missing 時,我們會檢查是否有相符的屬性方法。如果有,我們會指示 attribute_missing 分派屬性。此方法可以覆寫以自訂行為。

# File activemodel/lib/active_model/attribute_methods.rb, line 520
def attribute_missing(match, ...)
  __send__(match.proxy_target, match.attr_name, ...)
end

method_missing(method, ...)

允許存取物件屬性(儲存在由 attributes 傳回的雜湊中),就像它們是第一類別方法一樣。因此,一個具有 name 屬性的 Person 類別可以例如使用 Person#namePerson#name=,且從不直接使用屬性雜湊,除非使用 ActiveRecord::Base#attributes= 進行多重指派。

也可以實體化相關物件,因此,屬於 `clients` 資料表的 Client 類別,其中包含一個外來鍵 `master_id`,可以透過 Client#master 實體化 master。

# File activemodel/lib/active_model/attribute_methods.rb, line 507
def method_missing(method, ...)
  if respond_to_without_attributes?(method, true)
    super
  else
    match = matched_attribute_method(method.name)
    match ? attribute_missing(match, ...) : super
  end
end

respond_to?(method, include_private_methods = false)

# File activemodel/lib/active_model/attribute_methods.rb, line 528
def respond_to?(method, include_private_methods = false)
  if super
    true
  elsif !include_private_methods && super(method, true)
    # If we're here then we haven't found among non-private methods
    # but found among all methods. Which means that the given method is private.
    false
  else
    !matched_attribute_method(method.to_s).nil?
  end
end

respond_to_without_attributes?(method, include_private_methods = false)

具備 name 屬性的 Person 實例,可以詢問 person.respond_to?(:name)person.respond_to?(:name=)person.respond_to?(:name?),這三個函式皆會傳回 true

別名為:respond_to?