3

I have a class in my model written inside a vendor's code(which I cannot modify) which has a Proc attached to it. Considering an example for a shirt class, the code looks like the one below.

class Shirt < ActiveRecord::Base
  before_validation -> { self.size ||= 'medium' }
  # Some code here
end

(Note that this piece of code is setting the default shirt size)

Say,I now need to change the default shirt size to large in a decorator class. The code would look something like

Shirt.class_eval do
  before_validation -> { self.size ||= 'large' }
  # Some more code
end

However, the default shirt size is still set to medium since the before_validation callback in the original class is still called.

Is there a elegant way to remove the callback in the original code and use the class_eval validation instead?

Ramkumar K R
  • 195
  • 5
  • 13

2 Answers2

2

reset_callbacks removes all the callbacks for a certain event:

Shirt.class_eval do
  reset_callbacks(:before_validation)
end

This is a somewhat nuclear option as it removes all callbacks. But since the actual callback is not named you cannot just skip the particular callback anyways. I would consider fixing it upstream (or asking the author nicely if he can change the implementation to make it more modular).

max
  • 96,212
  • 14
  • 104
  • 165
1

You may skip before_validation before setting a new callback:

Shirt.class_eval do
  skip_callback :validation, :before
  before_validation -> { self.size ||= 'large' }
  # Some more code
end
Slava.K
  • 3,073
  • 3
  • 17
  • 28