Class: Zodra::TypeBuilder

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

Constant Summary collapse

PRIMITIVES =
i[string integer decimal boolean datetime date uuid binary number].freeze

Instance Method Summary collapse

Constructor Details

#initialize(definition) ⇒ TypeBuilder

Returns a new instance of TypeBuilder.



7
8
9
# File 'lib/zodra/type_builder.rb', line 7

def initialize(definition)
  @definition = definition
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *args) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
# File 'lib/zodra/type_builder.rb', line 40

def method_missing(method_name, *args, **, &)
  name_string = method_name.to_s
  optional = name_string.end_with?('?')
  scalar_name = optional ? name_string.delete_suffix('?').to_sym : method_name

  if ScalarRegistry.global.exists?(scalar_name)
    @definition.add_attribute(args.first, type: scalar_name, optional:, **)
  else
    super
  end
end

Instance Method Details

#array(name, of: nil) ⇒ Object



26
27
28
# File 'lib/zodra/type_builder.rb', line 26

def array(name, of: nil, **)
  @definition.add_attribute(name, type: :array, of:, **)
end

#from(type_name, pick: nil, omit: nil, partial: false) ⇒ Object



30
31
32
33
# File 'lib/zodra/type_builder.rb', line 30

def from(type_name, pick: nil, omit: nil, partial: false)
  source = TypeRegistry.global.find!(type_name)
  TypeDeriver.new(source, pick:, omit:, partial:).apply(@definition)
end

#reference(name, to: nil) ⇒ Object



21
22
23
24
# File 'lib/zodra/type_builder.rb', line 21

def reference(name, to: nil)
  target = to || name
  @definition.add_attribute(name, type: :reference, reference_name: target)
end

#respond_to_missing?(method_name, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


52
53
54
55
# File 'lib/zodra/type_builder.rb', line 52

def respond_to_missing?(method_name, include_private = false)
  scalar_name = method_name.to_s.delete_suffix('?').to_sym
  ScalarRegistry.global.exists?(scalar_name) || super
end

#timestampsObject



35
36
37
38
# File 'lib/zodra/type_builder.rb', line 35

def timestamps
  datetime :created_at
  datetime :updated_at
end