Home > Enterprise >  creating a class method for a active record attribute like has_attached_file
creating a class method for a active record attribute like has_attached_file

Time:09-03

I have seen in paperclip gem has_attached_file :avatar.

How can I create a method like this for models?

My objective is whenever i define attribute like custom_method :attribute i can run some active operation the data of attribute on active record callbacks like save and delete.

CodePudding user response:

It is just a class method.

def self.custom_method(attribute)
  before_save do
    do_stuff_with(attribute)
  end

  define_method "do_stuff_with_#{attribute}" do
    do_stuff_with(attribute)
  end

  do_other_stuff
end

You can either add it to your ApplicationRecord for it to be available everywhere or add it to a Concern/Mixin/Module that you can include when you want to use it.

  • Related