假设我们有一个名为“Items”的表、一个名为“name”的列和一个名为“quantity”的列。
那么假设我们有一个这样的 item 实例:
@item = Item.first
在此实例上您可以调用方法,例如:
@item.name.present?
@item.quantity.is_a?(Integer)
我将如何向所有列添加我自己的方法,例如,如果我想调用:
@item.name.custom_method?
@item.quantity.custom_method?
@item.name.custom_method_2(:xyz)
@item.quantity.custom_method_2(:xyz)
因此,我想向所有列属性(每个属性)添加方法,并用它来做一件自定义的事情。我已经看到了它的一些精华,例如 Rails 就用 dirty 来实现它,并将
changed?
添加到列/属性中。
您可以定义所谓的属性方法,这将为所有属性定义方法:
# app/models/model.rb
class Model < ApplicationRecord
attribute_method_suffix "_is_custom?"
private
def attribute_is_custom? attr
"#{attr} is custom."
end
end
>> Model.first.name_is_custom?
=> "name is custom."
>> Model.first.id_is_custom?
=> "id is custom."
https://api.rubyonrails.org/classes/ActiveRecord/AttributeMethods.html