Class: RubyAPI::Schema

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

Defined Under Namespace

Classes: ValidationError

Class Method Summary collapse

Class Method Details

.field(name, type: String) ⇒ Object



12
13
14
15
# File 'lib/rubyapi/schema.rb', line 12

def self.field(name, type: String)
  @fields ||= {}
  @fields[name] = type
end

.fieldsObject



17
18
19
# File 'lib/rubyapi/schema.rb', line 17

def self.fields
  @fields || {}
end

.inherited(subclass) ⇒ Object



21
22
23
# File 'lib/rubyapi/schema.rb', line 21

def self.inherited(subclass)
  subclass.instance_variable_set(:@fields, (@fields || {}).dup)
end

.validate(data) ⇒ Object

Raises:



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/rubyapi/schema.rb', line 25

def self.validate(data)
  errors = {}
  result = {}

  fields.each do |name, type|
    value = data.is_a?(Hash) ? (data[name.to_s] || data[name]) : nil
    if value.nil?
      errors[name] = "is required"
      next
    end
    begin
      result[name] = ParamConverters.convert(value, type)
    rescue ConversionError => e
      errors[name] = e.message
    end
  end

  raise ValidationError.new(errors) if errors.any?
  result
end