Class: RubyAPI::Schema
- Inherits:
-
Object
- Object
- RubyAPI::Schema
- Defined in:
- lib/fastrb/schema.rb
Defined Under Namespace
Classes: ValidationError
Class Method Summary collapse
- .field(name, type: String) ⇒ Object
- .fields ⇒ Object
- .inherited(subclass) ⇒ Object
- .validate(data) ⇒ Object
Class Method Details
.field(name, type: String) ⇒ Object
12 13 14 15 |
# File 'lib/fastrb/schema.rb', line 12 def self.field(name, type: String) @fields ||= {} @fields[name] = type end |
.fields ⇒ Object
17 18 19 |
# File 'lib/fastrb/schema.rb', line 17 def self.fields @fields || {} end |
.inherited(subclass) ⇒ Object
21 22 23 |
# File 'lib/fastrb/schema.rb', line 21 def self.inherited(subclass) subclass.instance_variable_set(:@fields, (@fields || {}).dup) end |
.validate(data) ⇒ Object
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
# File 'lib/fastrb/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. end end raise ValidationError.new(errors) if errors.any? result end |