在 ruby?? 中,您經常在實體化類時執行方法has_many或方法validates。是否有一個名稱來指定這種專門創建以在類實體化時呼叫的方法?
uj5u.com熱心網友回復:
基于Stefan 的出色評論......
它們是繼承的 類方法,形成用于宣告類的特定領域語言。
這些都是類方法,之所以這樣稱呼是因為您直接在類上呼叫 then 。self將是班級。與在類的實體上呼叫的實體方法相反,物件。
它們也是從繼承的方法ActiveRecord,它們不是在您的類中定義,而是在祖先類或模塊中定義。
更具體地說,它們形成了特定領域的語言;DSL。這些是以特定方式撰寫的方法呼叫,看起來像是一種新語言。例如,
class Player < ApplicationRecord
validates :terms_of_service, presence: true, acceptance: { message: 'must be abided' }
end
是真的...
Player.validates(
:terms_of_service,
presence: true,
acceptance: { message: 'must be abided' }
)
這是一個包裝...
Player.validates_presence_of(:terms_of_service)
Player.validates_acceptance_of(:terms_of_service, message: 'must be abided')
這是一個包裝...
Player.validates_with(PresenceValidator, :terms_of_service)
Player.validates_with(AcceptanceValidator, :terms_of_service, message: 'must be abided')
這是將驗證物件推送到此類的驗證哈希上的包裝器。
# Roughly...
Player._validators[:terms_of_service] <<
PresenceValidator.new(
attributes: [:terms_of_service]
)
Player._validators[:terms_of_service] <<
AcceptanceValidator.new(
attributes: [:terms_of_service],
message: 'must be abided'
)
最后,領域特定語言是宣告式編程的形式。
在其他型別的編程中,你告訴程式如何去做。例如,假設您想確保一個屬性是一個大于零的正整數。你可以按程式做...
object.number.match?(/^\d $/) && object.number > 0
或者你要求一個特定的方法來做到這一點......
NumericalityValidator.new(
attribute: [:number],
only_integer: true, greater_than: 0
).validate(object)
但是在宣告式編程中,您宣告它將如何發生,而語言會弄清楚如何實作它。
class Player < ApplicationRecord
validates :number, numericality: { only_integer: true, greater_than: 0 }
end
您可能已經知道兩種宣告性語言:SQL 和正則運算式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/389761.html
上一篇:了解哈希副本在幕后的行為方式
