File: definition.rb

package info (click to toggle)
ruby-clamp 1.1.1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 312 kB
  • sloc: ruby: 2,359; makefile: 4
file content (90 lines) | stat: -rw-r--r-- 2,198 bytes parent folder | download | duplicates (3)
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
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
require "clamp/attribute/definition"
require "clamp/truthy"

module Clamp
  module Option

    class Definition < Attribute::Definition

      def initialize(switches, type, description, options = {})
        @switches = Array(switches)
        @type = type
        @description = description
        super(options)
        @multivalued = options[:multivalued]
        return unless options.key?(:required)
        @required = options[:required]
        # Do some light validation for conflicting settings.
        raise ArgumentError, "Specifying a :default value with :required doesn't make sense" if options.key?(:default)
        raise ArgumentError, "A required flag (boolean) doesn't make sense." if type == :flag
      end

      attr_reader :switches, :type

      def long_switch
        switches.find { |switch| switch =~ /^--/ }
      end

      def handles?(switch)
        recognised_switches.member?(switch)
      end

      def flag?
        @type == :flag
      end

      def flag_value(switch)
        !(switch =~ /^--no-(.*)/ && switches.member?("--\[no-\]#{Regexp.last_match(1)}"))
      end

      def read_method
        if flag?
          super + "?"
        else
          super
        end
      end

      def extract_value(switch, arguments)
        if flag?
          flag_value(switch)
        else
          arguments.shift
        end
      end

      def default_conversion_block
        Clamp.method(:truthy?) if flag?
      end

      def help_lhs
        lhs = switches.join(", ")
        lhs += " " + type unless flag?
        lhs
      end

      private

      def recognised_switches
        switches.map do |switch|
          if switch =~ /^--\[no-\](.*)/
            ["--#{Regexp.last_match(1)}", "--no-#{Regexp.last_match(1)}"]
          else
            switch
          end
        end.flatten
      end

      def infer_attribute_name
        unless long_switch
          raise Clamp::DeclarationError, "You must specify either a long-switch or an :attribute_value"
        end
        inferred_name = long_switch.sub(/^--(\[no-\])?/, "").tr("-", "_")
        inferred_name += "_list" if multivalued?
        inferred_name
      end

    end

  end
end