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
- .apply_optional_key(parsed, optional_from_key) ⇒ Object
- .parse(type_def, **options) ⇒ Object
- .parse_declaration(attrs, **options) ⇒ Object
-
.parse_key(name) ⇒ Object
Strips a trailing ‘?` from an attribute key, returning [clean_name, optional?].
- .shortcut?(type_def) ⇒ Boolean
Class Method Details
.apply_optional_key(parsed, optional_from_key) ⇒ Object
59 60 61 62 |
# File 'lib/typelizer/type_parser.rb', line 59 def apply_optional_key(parsed, optional_from_key) parsed[:optional] = true if optional_from_key && !parsed.key?(:optional) parsed end |
.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 44 |
# File 'lib/typelizer/type_parser.rb', line 24 def parse(type_def, **) return if type_def.nil? return parse_shape(type_def, **) if type_def.is_a?(Hash) return parse_array(type_def, **) if type_def.is_a?(Array) type_str = type_def.to_s return parse_union(type_str, **) if type_str.include?("|") match = TYPE_PATTERN.match(type_str) return {type: type_def}.merge() 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() 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, **) return .merge(attrs) if attrs.is_a?(Hash) return parse(attrs, **) unless attrs.is_a?(Array) = attrs.last.merge() if attrs.last.is_a?(Hash) types = attrs.reject { |t| t.is_a?(Hash) } return if types.empty? parse((types.size == 1) ? types.first : types, **) end |
.parse_key(name) ⇒ Object
Strips a trailing ‘?` from an attribute key, returning [clean_name, optional?].
54 55 56 57 |
# File 'lib/typelizer/type_parser.rb', line 54 def parse_key(name) str = name.to_s str.end_with?("?") ? [str.chomp("?").to_sym, true] : [name.to_sym, false] end |
.shortcut?(type_def) ⇒ Boolean
46 47 48 49 50 51 |
# File 'lib/typelizer/type_parser.rb', line 46 def shortcut?(type_def) return false if type_def.nil? type_str = type_def.to_s type_str.end_with?("?", "[]") end |