Class: Oyster::Specification

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/oyster/specification.rb

Instance Method Summary collapse

Constructor Details

#initializeSpecification

Returns a new instance of Specification.



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

def initialize
  @options     = []
  @subcommands = []
  @data        = {}
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(*args) ⇒ Object



16
17
18
19
20
21
22
23
24
# File 'lib/oyster/specification.rb', line 16

def method_missing(*args)
  opt = Option.create(*args)
  raise "Option name '#{opt.name}' is already used" if has_option?(opt.name)
  opt.alternate(shorthand_for(opt.name))
  @options << opt
rescue
  name, value = args[0..1]
  @data[name.to_sym] = value.to_s
end

Instance Method Details

#command(name) ⇒ Object



40
41
42
43
44
45
# File 'lib/oyster/specification.rb', line 40

def command(name)
  @subcommands.each do |command|
    return command if command.has_name?(name)
  end
  nil
end

#each(&block) ⇒ Object



12
13
14
# File 'lib/oyster/specification.rb', line 12

def each(&block)
  @options.sort_by { |o| o.name.to_s }.each(&block)
end

#has_command?(name) ⇒ Boolean

Returns:

  • (Boolean)


36
37
38
# File 'lib/oyster/specification.rb', line 36

def has_command?(name)
  !command(name).nil?
end

#has_option?(name) ⇒ Boolean

Returns:

  • (Boolean)


32
33
34
# File 'lib/oyster/specification.rb', line 32

def has_option?(name)
  !self[name].nil?
end

#parse(input = ARGV) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/oyster/specification.rb', line 47

def parse(input = ARGV)
  input = input.dup
  output = {:unclaimed => []}
  
  while token = input.shift
    if token == '--'
      output[:unclaimed] = output[:unclaimed] + input
      break
    end
    
    option = command(token)
    
    long, short = token.scan(LONG_NAME), token.scan(SHORT_NAME)
    long, short = [long, short].map { |s| s.flatten.first }
    
    input = short.scan(/./).map { |s| "-#{s}" } + input and next if short and short.size > 1
    
    negative = !!(long && long =~ /^no-/)
    long.sub!(/^no-/, '') if negative
    
    option ||= self[long] || self[short]
    output[:unclaimed] << token and next unless option
    
    output[option.name] = option.is_a?(FlagOption) ? !negative : option.consume(input)
  end
  
  @options.each do |option|
    next unless output[option.name].nil?
    output[option.name] ||= option.default_value
  end
  
  help and raise HelpRendered if output[:help]
  output
end

#subcommand(name, &block) ⇒ Object



26
27
28
29
30
# File 'lib/oyster/specification.rb', line 26

def subcommand(name, &block)
  opt = SubcommandOption.new(name, Oyster.spec(&block))
  raise "Subcommand name '#{opt.name}' is already used" if has_command?(name)
  @subcommands << opt
end