summaryrefslogtreecommitdiff
path: root/lib/slop/option.rb
blob: fc023876f5ce1e7d8fd67a5ce99ab1ba3e11c918 (plain)
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
class Slop
  class Option

    # The default Hash of configuration options this class uses.
    DEFAULT_OPTIONS = {
      :argument => false,
      :optional_argument => false,
      :tail => false,
      :default => nil,
      :callback => nil,
      :delimiter => ',',
      :limit => 0,
      :match => nil,
      :optional => true,
      :required => false,
      :as => String,
      :autocreated => false
    }

    attr_reader :short, :long, :description, :config, :types
    attr_accessor :count
    attr_writer :value

    # Incapsulate internal option information, mainly used to store
    # option specific configuration data, most of the meat of this
    # class is found in the #value method.
    #
    # slop        - The instance of Slop tied to this Option.
    # short       - The String or Symbol short flag.
    # long        - The String or Symbol long flag.
    # description - The String description text.
    # config      - A Hash of configuration options.
    # block       - An optional block used as a callback.
    def initialize(slop, short, long, description, config = {}, &block)
      @slop = slop
      @short = short
      @long = long
      @description = description
      @config = DEFAULT_OPTIONS.merge(config)
      @count = 0
      @callback = block_given? ? block : config[:callback]
      @value = nil

      @types = {
        :string  => proc { |v| v.to_s },
        :symbol  => proc { |v| v.to_sym },
        :integer => proc { |v| value_to_integer(v) },
        :float   => proc { |v| value_to_float(v) },
        :array   => proc { |v| v.split(@config[:delimiter], @config[:limit]) },
        :range   => proc { |v| value_to_range(v) }
      }

      if long && long.size > @slop.config[:longest_flag]
        @slop.config[:longest_flag] = long.size
      end

      @config.each_key do |key|
        self.class.send(:define_method, "#{key}?") { !!@config[key] }
      end
    end

    # Returns true if this option expects an argument.
    def expects_argument?
      config[:argument] && config[:argument] != :optional
    end

    # Returns true if this option accepts an optional argument.
    def accepts_optional_argument?
      config[:optional_argument] || config[:argument] == :optional
    end

    # Returns the String flag of this option. Preferring the long flag.
    def key
      long || short
    end

    # Call this options callback if one exists, and it responds to call().
    #
    # Returns nothing.
    def call(*objects)
      @callback.call(*objects) if @callback.respond_to?(:call)
    end

    # Fetch the argument value for this option.
    #
    # Returns the Object once any type conversions have taken place.
    def value
      value = @value || config[:default]
      return if value.nil?

      type = config[:as]
      if type.respond_to?(:call)
        type.call(value)
      else
        if callable = types[type.to_s.downcase.to_sym]
          callable.call(value)
        else
          value
        end
      end
    end

    # Returns the help String for this option.
    def to_s
      return config[:help] if config[:help].respond_to?(:to_str)

      out = "    "
      out += short ? "-#{short}, " : ' ' * 4

      if long
        out += "--#{long}"
        size = long.size
        diff = @slop.config[:longest_flag] - size
        out += " " * (diff + 6)
      else
        out += " " * (@slop.config[:longest_flag] + 8)
      end

      "#{out}#{description}"
    end
    alias help to_s

    # Returns the String inspection text.
    def inspect
      "#<Slop::Option [-#{short} | --#{long}" +
      "#{'=' if expects_argument?}#{'=?' if accepts_optional_argument?}]" +
      " (#{description}) #{config.inspect}"
    end

    private

    # Convert an object to an Integer if possible.
    #
    # value - The Object we want to convert to an integer.
    #
    # Returns the Integer value if possible to convert, else a zero.
    def value_to_integer(value)
      if @slop.config[:strict]
        begin
          Integer(value.to_s, 10)
        rescue ArgumentError
          raise InvalidArgumentError,
                "#{value} could not be coerced into Integer"
        end
      else
        value.to_s.to_i
      end
    end

    # Convert an object to a Float if possible.
    #
    # value - The Object we want to convert to a float.
    #
    # Returns the Float value if possible to convert, else a zero.
    def value_to_float(value)
      if @slop.config[:strict]
        begin
          Float(value.to_s)
        rescue ArgumentError
          raise InvalidArgumentError, "#{value} could not be coerced into Float"
        end
      else
        value.to_s.to_f
      end
    end

    # Convert an object to a Range if possible.
    #
    # value - The Object we want to convert to a range.
    #
    # Returns the Range value if one could be found, else the original object.
    def value_to_range(value)
      case value.to_s
      when /\A(\-?\d+)\z/
        Range.new($1.to_i, $1.to_i)
      when /\A(-?\d+?)(\.\.\.?|-|,)(-?\d+)\z/
        Range.new($1.to_i, $3.to_i, $2 == '...')
      else
        if @slop.config[:strict]
          raise InvalidArgumentError, "#{value} could not be coerced into Range"
        else
          value
        end
      end
    end

  end
end