Search code examples
ruby-on-railsrubyactiverecord

In Rails how I add a "helper" method to an attribute / column?


Let's say we have an table called "Items" and a column named "name" and one named "quantity".

Then let's say we have an instance of item like this:

@item = Item.first

On this instance you can call methods, for example:

@item.name.present?
@item.quantity.is_a?(Integer)

How would I go about adding my own method to all columns, for example if I wanted to call:

@item.name.custom_method?
@item.quantity.custom_method?
@item.name.custom_method_2(:xyz)
@item.quantity.custom_method_2(:xyz)

So I'd like to add methods to all columns attributes, each one and do a custom thing with it. I've seen some gems to it and Rails does it with dirty for example and adds changed? to columns/attributes.


Solution

  • You can define what's called attribute methods which will in turn define methods for all attributes:

    # 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/ActiveModel/AttributeMethods.html