Attribute Methods
class Person
include ActiveModel::AttributeMethods
# 前缀
attribute_method_prefix 'clear_'
# 后缀
attribute_method_suffix '_contrived?'
# 前缀 + 后缀
attribute_method_affix prefix: 'reset_', suffix: '_to_default!'
# 要处理的属性
define_attribute_methods :name
attr_accessor :name
# 供查询属性及值
def attributes
{ 'name' => @name }
end
private
# 用 attribute 代替上面要处理的属性,加上前缀、后缀得到新的方法名,然后实现它们
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最后更新于