Class: TokenString

Inherits:
Object
  • Object
show all
Defined in:
lib/token_string.rb

Defined Under Namespace

Classes: Format, Impl, NoSuchConverterError

Class Method Summary collapse

Class Method Details

.add(name, format) ⇒ Object

Register a Format.

Registering a format adds that format to the available formats and creates two accessors on Impl instances: the name of the #<format> which creates a copy of the Impl with the requested format, and #<format>! which clones then sets the format.



32
33
34
35
36
37
38
39
40
# File 'lib/token_string.rb', line 32

def self.add name, format
  @converters = {} unless @converters
  @converters[name] = format
  # Register a converter for Impl

  Impl.class_eval([
    "def #{name}; Impl.new(:#{name}, @tokens); end",
    "def #{name}!; clone.force(:#{name}); end",
  ].join("\n") )
end

.convert_tokens_to(stream, format) ⇒ Object

Helper to convert a list of tokens to a specific format



43
44
45
46
47
# File 'lib/token_string.rb', line 43

def self.convert_tokens_to( stream, format )
  c_to = @converters[format]
  return str unless c_to
  c_to.convert_to( stream )
end

.from(format, string) ⇒ Object

Creates a new TokenString from the given string using the supplied format.

If no such format is registered, the method throws an NoSuchConverterError.

If the converter finds the string invalid, it throws an ArgumentError.



62
63
64
65
66
67
68
69
70
# File 'lib/token_string.rb', line 62

def self.from( format, string )
  converter = @converters[format]
  unless converter
    raise NoSuchConverterError.new(
      "Unknown format for input: #{format.inspect}." +
      "Available formats: #{@converters.keys.inspect}")
  end
  Impl.new( format, converter.convert_from( string ) )
end

.known_formatsObject

Gets a list of all the known formats.



50
51
52
# File 'lib/token_string.rb', line 50

def self.known_formats
  @converters.keys
end

.make(format, *tokens) ⇒ Object

Construct a new TokenString from the format and tokens.



74
75
76
# File 'lib/token_string.rb', line 74

def self.make( format, *tokens )
  Impl.new( format, linearize_tokens(tokens.flatten) )
end