Active Model 属性方法
提供一种方法,用于向你的方法添加前缀和后缀,以及处理 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/ |
FORWARD_PARAMETERS | = | "*args" |
NAME_COMPILABLE_REGEXP | = | /\A[a-zA-Z_]\w*[!?=]?\z/ |
实例公共方法
attribute_missing(match, *args, &block) 链接
attribute_missing
类似于 method_missing
,但适用于属性。当调用 method_missing
时,我们会检查是否存在匹配的属性方法。如果存在,我们会告诉 attribute_missing
分派属性。可以重载此方法以自定义行为。
来源:显示 | 在 GitHub 上
# File activemodel/lib/active_model/attribute_methods.rb, line 498 def attribute_missing(match, *args, &block) __send__(match.proxy_target, match.attr_name, *args, &block) end
method_missing(method, *args, &block) 链接
允许访问对象属性,这些属性保存在 attributes
返回的哈希中,就像它们是一流方法一样。因此,具有 name
属性的 Person
类可以例如使用 Person#name
和 Person#name=
,并且永远不会直接使用属性哈希 – 除了使用 ActiveRecord::Base#attributes=
进行多重赋值。
还可以实例化相关对象,因此属于 clients
表且具有 master_id
外键的 Client
类可以通过 Client#master
实例化 master。
来源:显示 | 在 GitHub 上
# File activemodel/lib/active_model/attribute_methods.rb, line 484 def method_missing(method, *args, &block) if respond_to_without_attributes?(method, true) super else match = matched_attribute_method(method.to_s) match ? attribute_missing(match, *args, &block) : super end end
respond_to?(method, include_private_methods = false) 链接
来源:显示 | 在 GitHub 上
# File activemodel/lib/active_model/attribute_methods.rb, line 507 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
。