Class: Ask::Schema::DSL::ConditionalBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/ask/schema/dsl/conditionals.rb

Overview

Builder for collecting requirements and validations within a conditional clause.

Constant Summary collapse

VALIDATES_KEY_MAP =

Map of validated option names to JSON Schema key names.

{
  type: :type,
  const: :const,
  enum: :enum,
  not_value: :not,
  min_length: :minLength,
  max_length: :maxLength,
  pattern: :pattern,
  minimum: :minimum,
  maximum: :maximum
}.freeze

Instance Method Summary collapse

Instance Method Details

#empty?Boolean

Check if the builder has no requirements or validations.

Returns:

  • (Boolean)


213
214
215
# File 'lib/ask/schema/dsl/conditionals.rb', line 213

def empty?
  required.empty? && validations.empty?
end

#required_fieldsArray<String>

Get the required field names (duped).

Returns:

  • (Array<String>)


219
220
221
# File 'lib/ask/schema/dsl/conditionals.rb', line 219

def required_fields
  required.dup
end

#requires(*fields) ⇒ Object

Mark fields as required.

Parameters:

  • fields (Array<Symbol, String>)

    Field names



160
161
162
# File 'lib/ask/schema/dsl/conditionals.rb', line 160

def requires(*fields)
  required.concat(fields.map(&:to_s))
end

#to_schemaHash

Convert to a JSON Schema fragment.

Returns:

  • (Hash)

    Schema fragment with required and properties



202
203
204
205
206
207
208
209
# File 'lib/ask/schema/dsl/conditionals.rb', line 202

def to_schema
  schema = {}

  schema[:required] = required if required.any?
  schema[:properties] = validations if validations.any?

  schema
end

#validates(field, **options) ⇒ Object

Add validation constraints for a field.

Parameters:

Raises:

  • (ArgumentError)

    If an unknown option is provided



182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'lib/ask/schema/dsl/conditionals.rb', line 182

def validates(field, **options)
  constraints = {}

  options.each do |key, value|
    schema_key = VALIDATES_KEY_MAP[key]
    raise ArgumentError, "unknown validates option: #{key.inspect}" unless schema_key

    case key
    when :type then constraints[:type] = value.to_s
    when :not_value then constraints[:not] = {const: value}
    when :pattern then constraints[:pattern] = value.is_a?(Regexp) ? value.source : value
    else constraints[schema_key] = value
    end
  end

  validations[field.to_s] = constraints
end

#validations_empty?Boolean

Check if no validations have been defined.

Returns:

  • (Boolean)


225
226
227
# File 'lib/ask/schema/dsl/conditionals.rb', line 225

def validations_empty?
  validations.empty?
end