DEV Community

n350071๐Ÿ‡ฏ๐Ÿ‡ต
n350071๐Ÿ‡ฏ๐Ÿ‡ต

Posted on

2 1

Append a method to all attributes with attribute_method_suffix in Rails

๐Ÿ”— Parent Note

๐Ÿ‘ You can add the same logic method to each attribute by write once

class Person < ActiveRecord::Base
  attribute_method_suffix '_changed?'
  attribute_method_suffix '_short?'

  private
    def attribute_changed?(attr)
      ...
    end
    def attribute_short?(attr)
      send(attr).length < 10
    end
end

person = Person.find(1)
person.name_changed?    # => false
person.name = 'Hubert'
person.name_changed?    # => true
person.name_short?      # => true
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“š attribute_method_suffix

Top comments (0)

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more