Module: Synthra::Relationships

Defined in:
lib/synthra/relationships.rb

Overview

Data Relationships Support

Provides expressive relationship types for schemas:

  • belongs_to(Schema) - Required reference
  • has_one(Schema) - Optional single reference
  • has_many(Schema, count) - Collection reference

Examples:

DSL syntax

Order:
  id: uuid
  user: belongs_to(User)
  items: has_many(OrderItem, 1..10)
  shipping_address?: has_one(Address)

Constant Summary collapse

TYPES =

Relationship type definitions

{
  belongs_to: { required: true, cardinality: :one },
  has_one: { required: false, cardinality: :one },
  has_many: { required: true, cardinality: :many }
}.freeze

Class Method Summary collapse

Class Method Details

.parse(type_str) ⇒ Hash?

Parse a relationship type from DSL

Parameters:

  • type_str (String)

    e.g., "belongs_to(User)"

Returns:

  • (Hash, nil)

    parsed relationship or nil if not a relationship



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/synthra/relationships.rb', line 31

def self.parse(type_str)
  return nil unless type_str.is_a?(String)

  TYPES.keys.each do |rel_type|
    pattern = /^#{rel_type}\((\w+)(?:,\s*(\d+)\.\.(\d+))?\)$/
    if (match = type_str.match(pattern))
      return {
        type: rel_type,
        target_schema: match[1],
        min_count: match[2]&.to_i || 1,
        max_count: match[3]&.to_i || 1,
        **TYPES[rel_type]
      }
    end
  end

  nil
end

.relationship?(type_str) ⇒ Boolean

Check if a type string is a relationship

Parameters:

  • type_str (String)

Returns:

  • (Boolean)


55
56
57
58
# File 'lib/synthra/relationships.rb', line 55

def self.relationship?(type_str)
  return false unless type_str.is_a?(String)
  TYPES.keys.any? { |t| type_str.start_with?("#{t}(") }
end

.to_standard_type(relationship) ⇒ String

Convert relationship to standard Synthra type

Parameters:

  • relationship (Hash)

    parsed relationship

Returns:

  • (String)

    equivalent standard type



65
66
67
68
69
70
71
72
# File 'lib/synthra/relationships.rb', line 65

def self.to_standard_type(relationship)
  case relationship[:cardinality]
  when :one
    relationship[:target_schema]
  when :many
    "array(#{relationship[:target_schema]}, #{relationship[:min_count]}..#{relationship[:max_count]})"
  end
end