Module: Cl::Cast

Included in:
Arg, Opt
Defined in:
lib/cl/cast.rb

Constant Summary collapse

TRUE =
/^(true|yes|on)$/
FALSE =
/^(false|no|off)$/

Instance Method Summary collapse

Instance Method Details

#cast(value) ⇒ Object


6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/cl/cast.rb', line 6

def cast(value)
  case type
  when nil
    value
  when :array
    Array(value).compact.flatten.map { |value| split(value) }.flatten
  when :string, :str
    value.to_s unless value.to_s.empty?
  when :flag, :boolean, :bool
    return true  if value.to_s =~ TRUE
    return false if value.to_s =~ FALSE
    !!value
  when :integer, :int
    Integer(value)
  when :float
    Float(value)
  else
    raise ArgumentError, "Unknown type: #{type}" if value
  end
rescue ::ArgumentError => e
  raise ArgumentError.new(:wrong_type, value.inspect, type)
end

#split(value) ⇒ Object


29
30
31
# File 'lib/cl/cast.rb', line 29

def split(value)
  separator ? value.to_s.split(separator) : value
end