Active Model
– Rails 的模型介面
Active Model
提供了一組已知的介面,可在模型類別中使用。例如,它們允許 Action Pack 輔助方法與非 Active Record 模型互動。 Active Model
還有助於構建在 Rails 框架之外使用的自定義 ORM。
您可以在《Active Model 基礎》指南中閱讀更多關於 Active Model
的資訊。
在 Rails 3.0 之前,如果插件或 gem 開發人員希望物件與 Action Pack 輔助方法互動,則需要從 Rails 複製程式碼片段,或猴子修補整個輔助方法以使其處理不完全符合 Active Record 介面的物件。這將導致程式碼重複和脆弱的應用程式在升級時損壞。Active Model
通過定義明確的 API
解決了這個問題。您可以在 `ActiveModel::Lint::Tests` 中閱讀更多關於 API
的資訊。
Active Model
提供了一個預設模組,該模組實現了與 Action Pack 立即整合所需的基本 API
:ActiveModel::API
。
class Person
include ActiveModel::API
attr_accessor :name, :age
validates_presence_of :name
end
person = Person.new(name: 'bob', age: '18')
person.name # => 'bob'
person.age # => '18'
person.valid? # => true
它包括模型名稱內省、轉換、翻譯和驗證,產生一個適用於 Action Pack 的類別。有關更多示例,請參閱 ActiveModel::API
。
Active Model
還提供以下功能,可以直接使用 ORM 類似行為
-
將屬性魔法添加到物件
class Person include ActiveModel::AttributeMethods attribute_method_prefix 'clear_' define_attribute_methods :name, :age attr_accessor :name, :age def clear_attribute(attr) send("#{attr}=", nil) end end person = Person.new person.clear_name person.clear_age
-
某些操作的
回呼
class Person extend ActiveModel::Callbacks define_model_callbacks :create def create run_callbacks :create do # Your create action methods here end end end
這會產生包裝 create 方法的 `before_create`、`around_create` 和 `after_create` 類別方法。
-
追蹤數值變化
class Person include ActiveModel::Dirty define_attribute_methods :name def name @name end def name=(val) name_will_change! unless val == @name @name = val end def save # do persistence work changes_applied end end person = Person.new person.name # => nil person.changed? # => false person.name = 'bob' person.changed? # => true person.changed # => ['name'] person.changes # => { 'name' => [nil, 'bob'] } person.save person.name = 'robert' person.save person.previous_changes # => {'name' => ['bob, 'robert']}
-
向物件新增 `errors` 介面
公開錯誤訊息允許物件與 Action Pack 輔助方法無縫互動。
class Person def initialize @errors = ActiveModel::Errors.new(self) end attr_accessor :name attr_reader :errors def validate! errors.add(:name, "cannot be nil") if name.nil? end def self.human_attribute_name(attr, options = {}) "Name" end end person = Person.new person.name = nil person.validate! person.errors.full_messages # => ["Name cannot be nil"]
-
模型
名稱內省class NamedPerson extend ActiveModel::Naming end NamedPerson.model_name.name # => "NamedPerson" NamedPerson.model_name.human # => "Named person"
-
使物件可序列化
ActiveModel::Serialization
為您的物件提供 `to_json` 序列化的標準介面。class SerialPerson include ActiveModel::Serialization attr_accessor :name def attributes {'name' => name} end end s = SerialPerson.new s.serializable_hash # => {"name"=>nil} class SerialPerson include ActiveModel::Serializers::JSON end s = SerialPerson.new s.to_json # => "{\"name\":null}"
-
國際化 (i18n) 支援
class Person extend ActiveModel::Translation end Person.human_attribute_name('my_attribute') # => "My attribute"
-
驗證支援
class Person include ActiveModel::Validations attr_accessor :first_name, :last_name validates_each :first_name, :last_name do |record, attr, value| record.errors.add attr, "starts with z." if value.start_with?("z") end end person = Person.new person.first_name = 'zoolander' person.valid? # => false
-
自定義驗證器
class HasNameValidator < ActiveModel::Validator def validate(record) record.errors.add(:name, "must exist") if record.name.blank? end end class ValidatorPerson include ActiveModel::Validations validates_with HasNameValidator attr_accessor :name end p = ValidatorPerson.new p.valid? # => false p.errors.full_messages # => ["Name must exist"] p.name = "Bob" p.valid? # => true
下載與安裝
最新版本的 Active Model
可以使用 RubyGems 安裝
$ gem install activemodel
原始碼可以作為 GitHub 上 Rails 專案的一部分下載
授權
Active Model
根據 MIT 授權發布
支援
API
文件位於
Ruby on Rails 專案的錯誤報告可以提交到這裡
功能請求應在 rails-core 郵件列表中討論
- 模組 ActiveModel::API
- 模組 ActiveModel::AttributeAssignment
- 模組 ActiveModel::AttributeMethods
- 模組 ActiveModel::Attributes
- 模組 ActiveModel::Callbacks
- 模組 ActiveModel::Conversion
- 模組 ActiveModel::Dirty
- 模組 ActiveModel::Lint
- 模組 ActiveModel::Model
- 模組 ActiveModel::Naming
- 模組 ActiveModel::SecurePassword
- 模組 ActiveModel::Serialization
- 模組 ActiveModel::Serializers
- 模組 ActiveModel::Translation
- 模組 ActiveModel::Type
- 模組 ActiveModel::VERSION
- 模組 ActiveModel::Validations
- 類別 ActiveModel::EachValidator
- 類別 ActiveModel::Error
- 類別 ActiveModel::Errors
- 類別 ActiveModel::ForbiddenAttributesError
- 類別 ActiveModel::MissingAttributeError
- 類別 ActiveModel::Name
- 類別 ActiveModel::NestedError
- 類別 ActiveModel::RangeError
- 類別 ActiveModel::StrictValidationFailed
- 類別 ActiveModel::UnknownAttributeError
- 類別 ActiveModel::ValidationError
- 類別 ActiveModel::Validator
- E
- G
- V
類別公開方法
eager_load!() 連結
來源:顯示 | 在 GitHub 上
# File activemodel/lib/active_model.rb, line 76 def self.eager_load! super ActiveModel::Serializers.eager_load! end
gem_version() 連結
將目前載入的 Active Model 版本作為 `Gem::Version` 返回。
來源:顯示 | 在 GitHub 上
# File activemodel/lib/active_model/gem_version.rb, line 5 def self.gem_version Gem::Version.new VERSION::STRING end
version() 連結
將目前載入的 Active Model 版本作為 `Gem::Version` 返回。
來源:顯示 | 在 GitHub 上
# File activemodel/lib/active_model/version.rb, line 7 def self.version gem_version end