Module: Sfn::CommandModule::Callbacks

Includes:
Bogo::Memoization
Included in:
Sfn::Command
Defined in:
lib/sfn/command_module/callbacks.rb

Overview

Callback processor helpers

Instance Method Summary collapse

Instance Method Details

#api_action!(*args) ⇒ Object

Run expected callbacks around action

Returns:

  • (Object)

    result of yield block



15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/sfn/command_module/callbacks.rb', line 15

def api_action!(*args)
  type = self.class.name.split("::").last.downcase
  run_callbacks_for(["before_#{type}", :before], *args)
  result = nil
  begin
    result = yield if block_given?
    run_callbacks_for(["after_#{type}", :after], *args)
    result
  rescue => err
    run_callbacks_for(["failed_#{type}", :failed], *(args + [err]))
    raise
  end
end

#callbacks_for(type) ⇒ Array<Method>

Fetch valid callbacks for given type

Parameters:

  • type (Symbol, String)

    name of callback type

  • responder (Array<String, Symbol>)

    matching response methods

Returns:

  • (Array<Method>)


57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/sfn/command_module/callbacks.rb', line 57

def callbacks_for(type)
  ([config.fetch(:callbacks, type, [])].flatten.compact + [config.fetch(:callbacks, :default, [])].flatten.compact).map do |c_name|
    instance = memoize(c_name) do
      begin
        klass = Sfn::Callback.const_get(Bogo::Utility.camel(c_name.to_s))
        klass.new(ui, config, arguments, provider)
      rescue NameError => e
        ui.debug "Callback type lookup error: #{e.class} - #{e}"
        raise NameError.new("Unknown #{type} callback requested: #{c_name} (not found)")
      end
    end
    if instance.respond_to?(type)
      [c_name, instance.method(type), instance.respond_to?(:quiet) ? instance.quiet : false]
    end
  end.compact
end

#run_callbacks_for(type, *args) ⇒ NilClass

Process requested callbacks

Parameters:

  • type (Symbol, String)

    name of callback type

Returns:

  • (NilClass)


33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/sfn/command_module/callbacks.rb', line 33

def run_callbacks_for(type, *args)
  types = [type].flatten.compact
  type = types.first
  clbks = types.map do |c_type|
    callbacks_for(c_type)
  end.flatten(1).compact.uniq.each do |item|
    callback_name, callback, quiet = item
    quiet = true if config[:print_only]
    ui.info "Callback #{ui.color(type.to_s, :bold)} #{callback_name}: #{ui.color("starting", :yellow)}" unless quiet
    if args.empty?
      callback.call
    else
      callback.call(*args)
    end
    ui.info "Callback #{ui.color(type.to_s, :bold)} #{callback_name}: #{ui.color("complete", :green)}" unless quiet
  end
  nil
end