Class: Drudge::Command

Inherits:
Object
  • Object
show all
Includes:
Parsers
Defined in:
lib/drudge/command.rb

Overview

Describes a command and helps executing it

The command is defined by a name and a list of arguments (see class Param). The body of the command is a lambda that accepts exactly the arguments

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Parsers

#arg, #command, #eos, #parser_mixin, #value

Methods included from Parsers::Primitives

#accept, #commit, #eos, #parser, #success

Methods included from Parsers::ParseResults::FactoryMethods

#Empty, #Error, #Failure, #Seq, #Single, #Success

Constructor Details

#initialize(name, params = [], body, desc: "") ⇒ Command

Initializes a new command



27
28
29
30
31
32
33
# File 'lib/drudge/command.rb', line 27

def initialize(name, params = [], body, desc: "")
  @name   = name.to_sym
  @params = params
  @body   = body

  @desc   = desc
end

Instance Attribute Details

#bodyObject (readonly)

The command’s body



21
22
23
# File 'lib/drudge/command.rb', line 21

def body
  @body
end

#descObject (readonly)

An optional short desicription of the command



24
25
26
# File 'lib/drudge/command.rb', line 24

def desc
  @desc
end

#nameObject (readonly)

The name of the command



15
16
17
# File 'lib/drudge/command.rb', line 15

def name
  @name
end

#paramsObject (readonly)

The list of parameters



18
19
20
# File 'lib/drudge/command.rb', line 18

def params
  @params
end

Instance Method Details

#argument_parserObject

creates an argument parser for the command



43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/drudge/command.rb', line 43

def argument_parser
  end_of_args = eos("extra command line arguments provided")

  parser = params.reverse.reduce(end_of_args) do |rest, param|
    p = param.argument_parser

    case
    when param.optional? then ((p > rest) | rest).describe("[#{p}] #{rest}")
    when param.splatt? then (p.repeats(till: rest) > rest).describe("[#{p} ...] #{rest}")
    else p > rest
    end
  end
end

#dispatch(*args) ⇒ Object

runs the command



36
37
38
39
40
# File 'lib/drudge/command.rb', line 36

def dispatch(*args)
  @body.call(*args)
rescue ArgumentError => e
  raise CommandArgumentError.new(name), e.message
end