Class: Docopt

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

Defined Under Namespace

Classes: Option, UnknownOptionError

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(doc, version = nil, help = true) ⇒ Docopt

Returns a new instance of Docopt.



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/docopt.rb', line 64

def initialize(doc, version=nil, help=true)
  @docopts = doc.split(/^ *-|\n *-/)[1..-1].map do |line|
    Option.new('-' + line)
  end
  
  GetoptLong.new(*docopts.map(&:getopt)).each do |opt, arg|
    docopt_option = option(opt)
    if help and (opt == '--help' or opt == '-h')
      puts doc.strip
      exit
    elsif version and opt == '--version'
      puts version
      exit
    else
      option.set_value arg
    end
  end
end

Instance Attribute Details

#docoptsObject (readonly)

Returns the value of attribute docopts.



4
5
6
# File 'lib/docopt.rb', line 4

def docopts
  @docopts
end

Instance Method Details

#inspectObject



102
103
104
105
106
# File 'lib/docopt.rb', line 102

def inspect
  @docopts.map do |option|
    "#{option.short} #{option.long}=#{option.value.inspect}".strip
  end.join("\n")
end

#option(name) ⇒ Object

Raises:



83
84
85
86
87
88
89
# File 'lib/docopt.rb', line 83

def option name
  option = @docopts.detect do |docopt|
    docopt.synonyms.include?(name)
  end
  raise UnknownOptionError.new("#{name} option not found") unless option
  option
end

#sizeObject



98
99
100
# File 'lib/docopt.rb', line 98

def size
  @docopts.size
end

#value(name) ⇒ Object Also known as: []



93
94
95
# File 'lib/docopt.rb', line 93

def value name
  option(name).value
end