Active Model Attribute Methods¶ ↑
提供了一种为方法添加前缀和后缀的方法,同时处理 ActiveRecord::Base 类方法(如 table_name)的创建。
实现 ActiveModel::AttributeMethods 的要求是:
-
在你的类中 `include ActiveModel::AttributeMethods`。
-
调用你想要添加的每个方法,例如
attribute_method_suffix或attribute_method_prefix。 -
在调用其他方法后,调用
define_attribute_methods。 -
定义你已声明的各种通用
_attribute方法。 -
定义一个
attributes方法,该方法返回一个哈希,其中模型中的每个属性名称都作为哈希键,属性值作为哈希值。Hash键必须是字符串。
一个最小化的实现可以是
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
常量
| 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 来分派属性。此方法可以被重载以自定义行为。
源文件: 显示 | 在 GitHub 上
# 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#name 和 Person#name=,而无需直接使用 attributes 哈希 - 除非是使用 ActiveRecord::Base#attributes= 进行多重赋值。
也可以实例化相关对象,因此属于 clients 表并且具有 master_id 外键的 Client 类可以通过 Client#master 实例化 master。
源文件: 显示 | 在 GitHub 上
# 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) 链接
源文件: 显示 | 在 GitHub 上
# 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。