Class: EasyTalk::Property

Inherits:
Object
  • Object
show all
Extended by:
T::Sig
Defined in:
lib/easy_talk/property.rb

Overview

Property class for building a JSON schema property.

This class handles the conversion from Ruby types to JSON Schema property definitions, and provides support for common constraints like minimum/maximum values, string patterns, and custom validators.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, type = nil, constraints = {}) ⇒ Property

Returns a new instance of Property.

Raises:

  • (ArgumentError)


68
69
70
71
72
73
74
75
76
77
# File 'lib/easy_talk/property.rb', line 68

def initialize(name, type = nil, constraints = {})
  @name = name
  @type = type
  @constraints = constraints
  if type.nil? || (type.respond_to?(:empty?) && type.is_a?(String) && type.strip.empty?)
    raise ArgumentError,
          'property type is missing'
  end
  raise ArgumentError, 'property type is not supported' if type.is_a?(Array) && type.empty?
end

Instance Attribute Details

#constraintsHash<Symbol, Object> (readonly)

Returns Additional constraints applied to the property.

Returns:

  • (Hash<Symbol, Object>)

    Additional constraints applied to the property



48
49
50
# File 'lib/easy_talk/property.rb', line 48

def constraints
  @constraints
end

#nameSymbol (readonly)

Returns The name of the property.

Returns:

  • (Symbol)

    The name of the property



42
43
44
# File 'lib/easy_talk/property.rb', line 42

def name
  @name
end

#typeObject (readonly)

Returns The type definition of the property.

Returns:

  • (Object)

    The type definition of the property



45
46
47
# File 'lib/easy_talk/property.rb', line 45

def type
  @type
end

Instance Method Details

#as_json(*_args) ⇒ Object



135
136
137
# File 'lib/easy_talk/property.rb', line 135

def as_json(*_args)
  build.as_json
end

#buildObject



105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/easy_talk/property.rb', line 105

def build
  if nilable_type?
    build_nilable_schema
  elsif RefHelper.should_use_ref?(type, constraints)
    RefHelper.build_ref_schema(type, constraints)
  elsif (resolved = find_builder_for_type)
    builder_class, is_collection = resolved
    args = is_collection ? [name, type, constraints] : [name, constraints]
    builder_class.new(*args).build
  elsif type.respond_to?(:schema)
    # merge the top-level constraints from *this* property
    # e.g. :title, :description, :default, etc
    type.schema.merge!(constraints)
  else
    raise UnknownTypeError,
          "Unknown type '#{type.inspect}' for property '#{name}'. " \
          'Register a custom builder with EasyTalk.register_type or use a supported type.'
  end
end