summaryrefslogtreecommitdiff
path: root/lib/slop/result.rb
blob: 0d0a3abceb098e7d71c4b40919373cc303869c1b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
module Slop
  # This class encapsulates a Parser and Option pair. The idea is that
  # the Option class shouldn't have to deal with what happens when options
  # are parsed, and the Parser shouldn't have to deal with the state of
  # options once parsing is complete. This keeps the API really simple; A
  # Parser parses, Options handles options, and this class handles the
  # result of those actions. This class contains the important most used
  # methods.
  class Result
    attr_reader :parser, :options

    def initialize(parser)
      @parser  = parser
      @options = parser.options
    end

    # Returns an options value, nil if the option does not exist.
    def [](flag)
      (o = option(flag)) && o.value
    end

    # Returns an Option if it exists. Ignores any prefixed hyphens.
    def option(flag)
      cleaned = -> (f) { f.to_s.sub(/\A--?/, '') }
      options.find do |o|
        o.flags.any? { |f| cleaned.(f) == cleaned.(flag) }
      end
    end

    def used_options
      parser.used_options
    end

    def unused_options
      parser.unused_options
    end

    # Returns a hash with option key => value.
    def to_hash
      Hash[options.map { |o| [o.key, o.value] }]
    end
  end
end