module Mandate::Callbacks

Public Class Methods

extended(base) click to toggle source
# File lib/mandate/callbacks.rb, line 59
def self.extended(base)
  base.send(:define_method, :call_with_callbacks) do
    begin
      # Create results object
      @__mandate_results = Results.new

      # Run the actual command
      # If call fails, succeeded! will never get called
      @__mandate_results.succeeded!(call)
    rescue AbortError
    end

    @__mandate_results
  end

  private

  base.send(:define_method, :add_error!) do |error|
    @__mandate_results.add_error(error)
  end

  base.send(:define_method, :abort!) do |error = nil|
    add_error!(error) if error
    raise AbortError
  end

  base.send(:define_method, :abort_if_errored!) do
    raise AbortError if @__mandate_results.errors.size > 0
  end
end
included(base) click to toggle source
# File lib/mandate/callbacks.rb, line 42
def self.included(base)
  # Override self.call to call the internal call_with_callbacks
  # function which returns a method with on_success/on_failure callbacks
  class << base
    # Remove the existing created by the "include Mandate"
    remove_method(:call)

    # Define a new call methods which calls the instance call
    # method but with the added callbacks needed for on_success/on_failure
    def call(*args)
      new(*args).call_with_callbacks
    end
  end

  base.extend(Callbacks)
end