Module: Ame::Types

Defined in:
lib/ame-1.0/types.rb

Overview

Types registered with Ame for parsing command-line arguments into Ruby values. By default, Ruby classes TrueClass, FalseClass, Float, Integer, String, and Symbol are registered, as well as an Enumeration type for limiting a Symbol to one of a fixed set.

Defined Under Namespace

Modules: Boolean, Float, Integer, String, Symbol Classes: Enumeration

Class Method Summary collapse

Class Method Details

.[](class_or_value) ⇒ Object

Returns The type registered to parse arguments into values of CLASS_OR_VALUE or of the class of CLASS_OR_VALUE, alternatively using CLASS_OR_VALUE itself if it responds to #parse.

Returns:

  • (Object)

    The type registered to parse arguments into values of CLASS_OR_VALUE or of the class of CLASS_OR_VALUE, alternatively using CLASS_OR_VALUE itself if it responds to #parse

Raises:

  • (ArgumentError)

    If a type that handles CLASS_OR_VALUE hasn’t been registered



53
54
55
56
57
58
# File 'lib/ame-1.0/types.rb', line 53

def [](class_or_value)
  type = @types[class_or_value] and return type
  pair = @types.find{ |c, t| class_or_value.is_a? c } and return pair.last
  class_or_value.respond_to? :parse and return class_or_value
  raise ArgumentError, 'unknown type: %p' % [class_or_value]
end

.register(type, *classes) ⇒ self

Registers TYPE for parsing command-line arguments for Ruby values whose class is any of CLASSES. The TYPE should respond to #parse(String), which should convert its String argument into a Ruby value, and may optionally respond to #default, which should return the default value of the TYPE, if any.

Examples:

Registering a New Type

require 'pathname'

module My::Pathname
  Ame::Types.register self, Pathname

  def parse(argument)
    Pathname(argument)
  end
end

Using a New Type as a Type

class Rm < Ame::Root
  
  splus 'FILE', My::Pathname, 'File to remove'
  def rm(pathnames)
    pathnames.each do |e| e.rmtree end
  end
end

Using a New Types as a Default

class My < Ame::Root
  optional 'CONFIG', Pathname('/etc/my/config'), 'Configuration file to use'

Parameters:

  • type (#parse, #default)
  • classes (::Class, )

Returns:

  • (self)


40
41
42
43
44
45
# File 'lib/ame-1.0/types.rb', line 40

def register(type, *classes)
  classes.each do |c|
    @types[c] = type
  end
  self
end