Class: Drudge::Command
- Inherits:
-
Object
- Object
- Drudge::Command
- 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
-
#body ⇒ Object
readonly
The command’s body.
-
#desc ⇒ Object
readonly
An optional short desicription of the command.
-
#name ⇒ Object
readonly
The name of the command.
-
#params ⇒ Object
readonly
The list of parameters.
Instance Method Summary collapse
-
#argument_parser ⇒ Object
creates an argument parser for the command.
-
#dispatch(*args) ⇒ Object
runs the command.
-
#initialize(name, params = [], body, desc: "") ⇒ Command
constructor
Initializes a new command.
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
#body ⇒ Object (readonly)
The command’s body
21 22 23 |
# File 'lib/drudge/command.rb', line 21 def body @body end |
#desc ⇒ Object (readonly)
An optional short desicription of the command
24 25 26 |
# File 'lib/drudge/command.rb', line 24 def desc @desc end |
#name ⇒ Object (readonly)
The name of the command
15 16 17 |
# File 'lib/drudge/command.rb', line 15 def name @name end |
#params ⇒ Object (readonly)
The list of parameters
18 19 20 |
# File 'lib/drudge/command.rb', line 18 def params @params end |
Instance Method Details
#argument_parser ⇒ Object
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. end |