Ruby on Rails Callback Classes

Ruby on Rails Callback Classes

If you want to reuse callback code for more than one object that Rails provides a way to write callback classes. All you have to do is pass a given callback queue an object that responds to the name of the callback and takes the model object as a parameter.

1
2
3
4
5
6
class MarkDeleted
  def self.before_destroy(model)
    model.update_attribute(:deleted_at, Time.current)
    false
  end
end

The behavior of MarkDeleted is stateless, so I added the callback as a class method.

1
2
3
class Account < ActiveRecord::Base
  before_destroy MarkDeleted
end
1
2
3
class Invoice < ActiveRecord::Base
  before_destroy MarkDeleted
end

So far so good, That’s it!!! See ya!!! :)