Module: Mandate::Callbacks

Defined in:
lib/mandate/callbacks.rb

Defined Under Namespace

Classes: AbortError, Results

Class Method Summary collapse

Class Method Details

.extended(base) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# 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
      # Used for flow handling
    end

    @__mandate_results
  end

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

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

  base.send(:define_method, :abort_if_errored!) do
    raise AbortError if @__mandate_results.errors.size > 0
  end
  base.send(:private, :abort_if_errored!)
end

.included(base) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# 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