Class: CommandParser

Inherits:
Object
  • Object
show all
Defined in:
lib/command_parser.rb

Overview

wrapper class for options parser

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ CommandParser

pass the config so we can access



6
7
8
9
10
# File 'lib/command_parser.rb', line 6

def initialize config
    @config = config
    @options = options
    @help_called = false
end

Instance Method Details

#collect(arguments) ⇒ Object

collect the command arguments via the option parser class



18
19
20
21
22
23
24
25
26
27
28
29
30
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
# File 'lib/command_parser.rb', line 18

def collect(arguments)
    # build the class options from options parser instance
    parser = OptionParser.new do |opts|
        opts.banner = "Options for output grasshopper"
        opts.separator "\n"
        opts.separator "Specifics:"

        opts.on('-m [name]', '--motivate [name]', String, "# Output a motivational quote") do |m|
            @options[:method] = 'motivate'
            @options[:arguments] = { author: m }
        end            

        opts.on('-w [glob1,glob2] ', '--watch [glob1,glob2]', Array, '# Watch files & output a message on file/folder change event') do |w|
            @options[:method] = 'watch'
            @options[:arguments] = { files: w }
        end

        opts.on_tail('-h', '--help', '# Output command line help options') do 
            @help_called = true
            puts opts
            exit(1)
        end
    end

    # set the options from calling the parser if there are any exceptions
    # we need to catch them and output the help message
    begin
        parser.parse!(arguments)    
    rescue Exception => e
        if not(e.kind_of? SystemExit)
            puts parser
            exit(1)    
        end
    end

    # if no valid methods were set we can't execute and therefore we exit and
    # put the parser message to the console
    if @options[:method].nil?
        puts parser if not @help_called
        exit(1)
    end

    #return the options
    @options
end

#optionsObject

default options



13
14
15
# File 'lib/command_parser.rb', line 13

def options
    { method: nil, arguments: nil}
end

#output_authorsObject

output a prett list of authors



65
66
67
68
69
70
71
72
73
# File 'lib/command_parser.rb', line 65

def output_authors
    authors = []

    @config['quotes'].each do |author|
        authors << author[0]
    end

    authors.join(', ')
end