Module: Kontena::Command::Finalizer

Defined in:
lib/kontena/command.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extended(obj) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
# File 'lib/kontena/command.rb', line 19

def self.extended(obj)
  # Tracepoint is used to trigger finalize once the command is completely
  # loaded. If done through def self.inherited the finalizer and
  # after_load callbacks would run before the options are defined.
  TracePoint.trace(:end) do |t|
    if obj == t.self
      obj.finalize
      t.disable
    end
  end
end

Instance Method Details

#finalize ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/kontena/command.rb', line 31

def finalize
  return if self.has_subcommands?
  return if self.callback_matcher

  name_parts = self.name.split('::')[-2, 2]

  unless name_parts.compact.empty?
    # 1: Remove trailing 'Command' from for example AuthCommand
    # 2: Convert the string from CamelCase to under_score
    # 3: Convert the string into a symbol
    #
    # In comes: ['ExternalRegistry', 'UseCommand']
    # Out goes: [:external_registry, :use]
    name_parts = name_parts.map { |np|
      np.gsub(/Command$/, '').
      gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
      gsub(/([a-z\d])([A-Z])/,'\1_\2').
      tr("-", "_").
      downcase.
      to_sym
    }
    self.callback_matcher(*name_parts)
  end

  # Run all #after_load callbacks for this command.
  [name_parts.last, :all].compact.uniq.each do |cmd_type|
    [name_parts.first, :all].compact.uniq.each do |cmd_class|
      if Kontena::Callback.callbacks.fetch(cmd_class, {}).fetch(cmd_type, nil)
        Kontena::Callback.callbacks[cmd_class][cmd_type].each do |cb|
          if cb.instance_methods.include?(:after_load)
            cb.new(self).after_load
          end
        end
      end
    end
  end
end