AttributeMethodsが正しく機能するためには、
attribute_method_prefix, attribute_method_suffixは
define_attribute_method 'age' の手前に書いておく必要があります。
公式チュートリアルのコード
class Person
include ActiveModel::AttributeMethods
attribute_method_prefix 'reset_'
attribute_method_suffix '_highest?'
define_attribute_methods 'age'
attr_accessor :age
private
def reset_attribute(attribute)
send("#{attribute}=", 0)
end
def attribute_highest?(attribute)
send(attribute) > 100
end
end
以下のようにちゃんと機能して動きます。
person = Person.new
person.age = 110
person.age_highest?
=> true
機能しないコード
class Person
include ActiveModel::AttributeMethods
define_attribute_methods 'age' #← attribute_method_prefixの手前にに定義してしまっている
attribute_method_prefix 'reset_'
attribute_method_suffix '_highest?'
attr_accessor :age
private
def reset_attribute(attribute)
send("#{attribute}=", 0)
end
def attribute_highest?(attribute)
send(attribute) > 100
end
end
person = Person.new
person.age = 110
person.age_highest?
=> NoMethodError undefined_method 'age_highest?'
順番で影響をうけるので、公式コードの書き方は素直に真似した方がよさそうです。