Module: Typelizer::TypeParser

Defined in:
lib/typelizer/type_parser.rb

Constant Summary collapse

TYPE_PATTERN =

Regex to match type shortcuts:

  • Base type (captured)

  • Optional ‘?` modifier

  • Optional [] modifier

Order of ? and [] can be either way

/\A(.+?)(\?)?(\[\])?(\?)?\z/

Class Method Summary collapse

Class Method Details

.parse(type_def, **options) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/typelizer/type_parser.rb', line 24

def parse(type_def, **options)
  return options if type_def.nil?
  return parse_array(type_def, **options) if type_def.is_a?(Array)

  type_str = type_def.to_s
  return parse_union(type_str, **options) if type_str.include?("|")

  match = TYPE_PATTERN.match(type_str)

  return {type: type_def}.merge(options) unless match

  base_type = match[1]
  optional = match[2] == "?" || match[4] == "?"
  multi = match[3] == "[]"

  result = {type: base_type.to_sym}
  result[:optional] = true if optional
  result[:multi] = true if multi
  result.merge(options)
end

.parse_declaration(attrs, **options) ⇒ Object



13
14
15
16
17
18
19
20
21
22
# File 'lib/typelizer/type_parser.rb', line 13

def parse_declaration(attrs, **options)
  return options.merge(attrs) if attrs.is_a?(Hash)
  return parse(attrs, **options) unless attrs.is_a?(Array)

  options = attrs.last.merge(options) if attrs.last.is_a?(Hash)
  types = attrs.reject { |t| t.is_a?(Hash) }
  return options if types.empty?

  parse((types.size == 1) ? types.first : types, **options)
end

.shortcut?(type_def) ⇒ Boolean

Returns:

  • (Boolean)


45
46
47
48
49
50
# File 'lib/typelizer/type_parser.rb', line 45

def shortcut?(type_def)
  return false if type_def.nil?

  type_str = type_def.to_s
  type_str.end_with?("?", "[]")
end