Class: HTTPDisk::Sloptions

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

Overview

Like Slop, but for sanity checking method options. Useful for library entry points that want to be strict. Example usage:

options = Sloptions.new(options) do

_1.boolean :force
_1.integer :retries, required: true
_1.string :hello, default: 'world'
...

end

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize {|_self| ... } ⇒ Sloptions

Returns a new instance of Sloptions.

Yields:

  • (_self)

Yield Parameters:



18
19
20
21
# File 'lib/httpdisk/sloptions.rb', line 18

def initialize
  @flags = {}
  yield(self)
end

Instance Attribute Details

#flagsObject (readonly)

Returns the value of attribute flags.



12
13
14
# File 'lib/httpdisk/sloptions.rb', line 12

def flags
  @flags
end

Class Method Details

.parse(options, &block) ⇒ Object



14
15
16
# File 'lib/httpdisk/sloptions.rb', line 14

def self.parse(options, &block)
  Sloptions.new(&block).parse(options)
end

Instance Method Details

#on(flag, foptions = {}) ⇒ Object

_1.on and friends



27
28
29
30
31
# File 'lib/httpdisk/sloptions.rb', line 27

def on(flag, foptions = {})
  raise ":#{flag} already defined" if flags[flag]

  flags[flag] = foptions
end

#parse(options) ⇒ Object

return parsed options



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/httpdisk/sloptions.rb', line 44

def parse(options)
  # defaults
  options = defaults.merge(options.compact)

  flags.each do |flag, foptions|
    # nil check
    value = options[flag]
    if value.nil?
      raise ArgumentError, ":#{flag} is required" if foptions[:required]

      next
    end

    # type cast (for boolean)
    if foptions[:type] == :boolean
      value = options[flag] = !!options[flag]
    end

    # type check
    types = Array(foptions[:type])
    raise ArgumentError, error_message(flag, value, types) if !valid?(value, types)
  end

  # return
  options
end