Module: Etna::CommandExecutor

Overview

Include this module into class that dispatches to child CommandExecutors | Commands that must exist as inner classes. Note that non-root CommandExecutors must accept and set their @parent just like commands.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#parentObject (readonly)

Returns the value of attribute parent.



163
164
165
# File 'lib/etna/command.rb', line 163

def parent
  @parent
end

Class Method Details

.included(cls) ⇒ Object



170
171
172
173
174
175
176
177
178
179
# File 'lib/etna/command.rb', line 170

def self.included(cls)
  cls.include(CommandOrExecutor)
  cls.const_set(:Help, Class.new(Etna::Command) do
    usage 'List this help'

    def execute
      self.parent.help
    end
  end) unless cls.const_defined?(:Help)
end

Instance Method Details

#all_subcommandsObject



214
215
216
# File 'lib/etna/command.rb', line 214

def all_subcommands
  subcommands.values + (subcommands.values.map { |s| s.respond_to?(:all_subcommands) ? s.all_subcommands : [] }.flatten)
end

#dispatch_to_subcommand(cmd = 'help', *args, **kwds) ⇒ Object



193
194
195
196
197
198
199
200
# File 'lib/etna/command.rb', line 193

def dispatch_to_subcommand(cmd = 'help', *args, **kwds)
  unless subcommands.include?(cmd)
    cmd = 'help'
    args = []
  end

  subcommands[cmd].find_command(*args, **kwds)
end

#find_command(*args, **kwds) ⇒ Object



188
189
190
191
# File 'lib/etna/command.rb', line 188

def find_command(*args, **kwds)
  flags, args = parse_flags(*args)
  dispatch_to_subcommand(*args, **(kwds.update(flags)))
end

#helpObject



181
182
183
184
185
186
# File 'lib/etna/command.rb', line 181

def help
  puts "usage: #{program_name} #{desc}"
  subcommands.each do |name, cmd|
    puts cmd.usage
  end
end

#initialize(parent = nil) ⇒ Object



165
166
167
168
# File 'lib/etna/command.rb', line 165

def initialize(parent = nil)
  super()
  @parent = parent
end

#subcommandsObject



202
203
204
205
206
207
208
209
210
211
212
# File 'lib/etna/command.rb', line 202

def subcommands
  @subcommands ||= self.class.constants.sort.reduce({}) do |acc, n|
    acc.tap do
      c = self.class.const_get(n)
      next unless c.respond_to?(:instance_methods)
      next unless c.instance_methods.include?(:find_command)
      v = c.new(self)
      acc[v.command_name] = v
    end
  end
end