mercredi 23 septembre 2020

Callback inside a Module

I have something similar to this:

Module A
    Class A
        def initialize
        end

        def A
        end

        def B
        end

        def C
        end
    end
end

What I want is to run a validation before A, B, or C is executed, like a before_action, to return nil if is a condition is satisfied, for instance, if a variable is nil, return nil immediately.

I know that I can create a module:

module Callbacks
  def callbacks
    @callbacks ||= Hash.new { |hash, key| hash[key] = [] }
  end

  def before_run(method_name, callback)
    callbacks[method_name] << callback
  end

  module InstanceMethods
    def run_callbacks_for(method_name)
      self.class.callbacks[method_name].to_a.each do |callback|
        send(callback)
      end
    end
  end
end

And inside the Class A, I can call:

before_run :A, :my_validation_method
before_run :B, :my_validation_method
before_run :C, :my_validation_method

Is there any other clean way of doing this?

Aucun commentaire:

Enregistrer un commentaire