Class: ZodRails::Generation::SchemaBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/zod_rails/generation/schema_builder.rb

Constant Summary collapse

STRING_TYPES =
%i[string text].freeze
NULLABILITY_SUFFIX_RE =
/(\.(?:nullable|nullish|optional)\(\))\z/
TYPESCRIPT_IDENTIFIER_RE =
/\A[$A-Z_a-z][$\w]*\z/

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(inspector, excluded_columns: [], schema_suffix: "Schema", input_schema_suffix: "InputSchema") ⇒ SchemaBuilder

Returns a new instance of SchemaBuilder.



12
13
14
15
16
17
# File 'lib/zod_rails/generation/schema_builder.rb', line 12

def initialize(inspector, excluded_columns: [], schema_suffix: "Schema", input_schema_suffix: "InputSchema")
  @inspector = inspector
  @excluded_columns = excluded_columns.map(&:to_s)
  @schema_suffix = schema_suffix
  @input_schema_suffix = input_schema_suffix
end

Instance Attribute Details

#excluded_columnsObject (readonly)

Returns the value of attribute excluded_columns.



10
11
12
# File 'lib/zod_rails/generation/schema_builder.rb', line 10

def excluded_columns
  @excluded_columns
end

#input_schema_suffixObject (readonly)

Returns the value of attribute input_schema_suffix.



10
11
12
# File 'lib/zod_rails/generation/schema_builder.rb', line 10

def input_schema_suffix
  @input_schema_suffix
end

#inspectorObject (readonly)

Returns the value of attribute inspector.



10
11
12
# File 'lib/zod_rails/generation/schema_builder.rb', line 10

def inspector
  @inspector
end

#schema_suffixObject (readonly)

Returns the value of attribute schema_suffix.



10
11
12
# File 'lib/zod_rails/generation/schema_builder.rb', line 10

def schema_suffix
  @schema_suffix
end

Instance Method Details

#build(input_schema: false) ⇒ Object



19
20
21
22
23
24
25
26
# File 'lib/zod_rails/generation/schema_builder.rb', line 19

def build(input_schema: false)
  columns = input_schema ? filtered_columns : inspector.columns
  fields = columns.map do |column|
    field_definition(column, input_schema: input_schema)
  end

  "z.object({\n  #{fields.join(",\n  ")}\n})"
end

#schema_name(input_schema: false) ⇒ Object

Raises:



28
29
30
31
32
33
34
# File 'lib/zod_rails/generation/schema_builder.rb', line 28

def schema_name(input_schema: false)
  suffix = input_schema ? input_schema_suffix : schema_suffix
  name = "#{inspector.model_name.gsub("::", "")}#{suffix}"
  return name if name.match?(TYPESCRIPT_IDENTIFIER_RE)

  raise ZodRails::Error, "Invalid TypeScript schema name: #{name.inspect}"
end

#type_name(input_schema: false) ⇒ Object



36
37
38
39
# File 'lib/zod_rails/generation/schema_builder.rb', line 36

def type_name(input_schema: false)
  name = inspector.model_name.gsub("::", "")
  input_schema ? "#{name}Input" : name
end