Module: TTY::Option::Converter

Included in:
Conversions
Defined in:
lib/tty/option/converter.rb

Instance Method Summary collapse

Instance Method Details

#[](name) ⇒ Proc Also known as: fetch

Retrieve a conversion type

Parameters:

  • name (String)

Returns:

  • (Proc)


48
49
50
51
# File 'lib/tty/option/converter.rb', line 48

def [](name)
  conv_name = name.to_s.downcase.to_sym
  conversions.fetch(conv_name) { raise_unsupported_error(conv_name) }
end

#contain?(name) ⇒ Boolean

Check if conversion is available

Parameters:

  • name (String)

Returns:

  • (Boolean)


20
21
22
23
# File 'lib/tty/option/converter.rb', line 20

def contain?(name)
  conv_name = name.to_s.downcase.to_sym
  conversions.key?(conv_name)
end

#conversionsObject

Store conversions



9
10
11
# File 'lib/tty/option/converter.rb', line 9

def conversions
  @conversions ||= {}
end

#convert(*names, &block) ⇒ Object

Register a new conversion type

Examples:

convert(:int) { |val| Float(val).to_i }


31
32
33
34
35
36
37
38
39
# File 'lib/tty/option/converter.rb', line 31

def convert(*names, &block)
  names.each do |name|
    if contain?(name)
      raise ConversionAlreadyDefined,
            "conversion #{name.inspect} is already defined"
    end
    conversions[name] = block
  end
end

#raise_unsupported_error(conv_name) ⇒ Object

Raise an error for unknown conversion type



57
58
59
60
# File 'lib/tty/option/converter.rb', line 57

def raise_unsupported_error(conv_name)
  raise UnsupportedConversion,
        "unsupported conversion type #{conv_name.inspect}"
end