Class: Easyop::FieldSchema

Inherits:
Object
  • Object
show all
Defined in:
lib/easyop/schema.rb

Overview

Describes a set of typed fields (used for both params and result schemas).

Defined Under Namespace

Classes: Field

Constant Summary collapse

TYPE_MAP =
{
  string:  String,
  integer: Integer,
  float:   Float,
  boolean: [TrueClass, FalseClass],
  symbol:  Symbol,
  any:     BasicObject,
}.freeze

Instance Method Summary collapse

Constructor Details

#initializeFieldSchema

Returns a new instance of FieldSchema.



88
89
90
# File 'lib/easyop/schema.rb', line 88

def initialize
  @fields = []
end

Instance Method Details

#fieldsObject



100
101
102
# File 'lib/easyop/schema.rb', line 100

def fields
  @fields.dup
end

#optional(name, type = nil, **opts) ⇒ Object



96
97
98
# File 'lib/easyop/schema.rb', line 96

def optional(name, type = nil, **opts)
  add_field(name, type, required: false, **opts)
end

#required(name, type = nil, **opts) ⇒ Object



92
93
94
# File 'lib/easyop/schema.rb', line 92

def required(name, type = nil, **opts)
  add_field(name, type, required: true, **opts)
end

#validate!(ctx, phase: :params) ⇒ Object

Validate ctx against this schema. Raises Ctx::Failure on hard errors; emits warnings otherwise depending on Easyop.config.strict_types.



107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
# File 'lib/easyop/schema.rb', line 107

def validate!(ctx, phase: :params)
  @fields.each do |field|
    val = ctx[field.name]

    # Apply default if not set
    if val.nil? && field.has_default
      ctx[field.name] = field.default.respond_to?(:call) ? field.default.call : field.default
      val = ctx[field.name]
    end

    # Required check
    if field.required && val.nil?
      ctx.fail!(
        error:  "Missing required #{phase} field: #{field.name}",
        errors: ctx.errors.merge(field.name => "is required")
      )
    end

    # Type check (skip if nil and optional)
    next if val.nil?
    next if field.type.nil?

    type_check!(ctx, field, val, phase)
  end
end