Class: Twing::Initializer

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(pre = false) ⇒ Initializer

Returns a new instance of Initializer.



7
8
9
10
11
12
13
# File 'lib/twing/initializer.rb', line 7

def initialize(pre = false)
  @pre = pre
  @optparse = OptionParser.new
  @optparse.version = Twing::VERSION
  @options = {}
  @callbacks = {}
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



5
6
7
# File 'lib/twing/initializer.rb', line 5

def options
  @options
end

#optparseObject (readonly)

Returns the value of attribute optparse.



5
6
7
# File 'lib/twing/initializer.rb', line 5

def optparse
  @optparse
end

Instance Method Details

#add(key, *args, &block) ⇒ Object



15
16
17
18
# File 'lib/twing/initializer.rb', line 15

def add(key, *args, &block)
  @optparse.on(*args) { |v| @options[key] = v }
  @callbacks[key] = block if block
end

#call(options, root_options = options) ⇒ Object



34
35
36
37
38
# File 'lib/twing/initializer.rb', line 34

def call(options, root_options = options)
  options.each do |key, value|
    @callbacks[key].call(value, root_options) if @callbacks[key]
  end
end

#init(argv = ARGV, left = []) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/twing/initializer.rb', line 20

def init(argv = ARGV, left = [])
  @optparse.parse(argv - left)
  call(@options)
  left
rescue OptionParser::InvalidOption => e
  raise e unless @pre
  e.args.each do |arg|
    next_item = argv[argv.index(arg) + 1]
    left += e.args
    left << next_item if !next_item.nil? && !next_item.start_with?(?-)
  end
  init(argv, left)
end