Class: TypesFromSerializers::Interface

Inherits:
Struct
  • Object
show all
Defined in:
lib/types_from_serializers/generator.rb

Overview

Internal: Information to generate a TypeScript interface for a serializer.

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#filenameObject

Returns the value of attribute filename

Returns:

  • (Object)

    the current value of filename



112
113
114
# File 'lib/types_from_serializers/generator.rb', line 112

def filename
  @filename
end

#nameObject

Returns the value of attribute name

Returns:

  • (Object)

    the current value of name



112
113
114
# File 'lib/types_from_serializers/generator.rb', line 112

def name
  @name
end

#propertiesObject

Returns the value of attribute properties

Returns:

  • (Object)

    the current value of properties



112
113
114
# File 'lib/types_from_serializers/generator.rb', line 112

def properties
  @properties
end

Instance Method Details

#as_typescriptObject



145
146
147
148
149
150
151
152
# File 'lib/types_from_serializers/generator.rb', line 145

def as_typescript
  indent = TypesFromSerializers.config.namespace ? 3 : 1
  "    interface \#{name} {\n    \#{\"  \" * indent}\#{properties.index_by(&:name).values.map(&:as_typescript).join(\"\\n\#{\"  \" * indent}\")}\n    \#{\"  \" * (indent - 1)}}\n  TS\nend\n".gsub(/\n$/, "")

#inspectObject



120
121
122
# File 'lib/types_from_serializers/generator.rb', line 120

def inspect
  to_h.inspect
end

#used_importsObject

Internal: Returns a list of imports for types used in this interface.



125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# File 'lib/types_from_serializers/generator.rb', line 125

def used_imports
  association_serializers, attribute_types = properties.map(&:type).compact.uniq
    .partition { |type| type.respond_to?(:ts_interface) }

  serializer_type_imports = association_serializers.map(&:ts_interface)
    .map { |type| [type.name, relative_path(type.pathname, pathname)] }

  custom_type_imports = attribute_types
    .flat_map { |type| extract_typescript_types(type.to_s) }
    .uniq
    .reject { |type| global_type?(type) }
    .map { |type|
      type_path = TypesFromSerializers.config.relative_custom_types_dir.join(type)
      [type, relative_path(type_path, pathname)]
    }

  (custom_type_imports + serializer_type_imports)
    .map { |interface, filename| "import type #{interface} from '#{filename}'\n" }
end