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



16
17
18
19
20
21
22
# File 'lib/sfn/command_module/callbacks.rb', line 16

def api_action!(*args)
  type = self.class.name.split('::').last.downcase
  run_callbacks_for(["before_#{type}", :before], *args)
  result = yield if block_given?
  run_callbacks_for(["after_#{type}", :after], *args)
  result
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>)


51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/sfn/command_module/callbacks.rb', line 51

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
        raise "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)


28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/sfn/command_module/callbacks.rb', line 28

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
    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