Class: Sinatra::Schema::Definition

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Definition

Returns a new instance of Definition.



6
7
8
9
10
11
12
# File 'lib/sinatra/schema/definition.rb', line 6

def initialize(options={})
  @description = options[:description]
  @example     = options[:example]
  @id          = options[:id]
  @optional    = options[:optional]
  @type        = options[:type]
end

Instance Attribute Details

#descriptionObject

Returns the value of attribute description.



4
5
6
# File 'lib/sinatra/schema/definition.rb', line 4

def description
  @description
end

#exampleObject

Returns the value of attribute example.



4
5
6
# File 'lib/sinatra/schema/definition.rb', line 4

def example
  @example
end

#idObject

Returns the value of attribute id.



4
5
6
# File 'lib/sinatra/schema/definition.rb', line 4

def id
  @id
end

#optionalObject

Returns the value of attribute optional.



4
5
6
# File 'lib/sinatra/schema/definition.rb', line 4

def optional
  @optional
end

#typeObject

Returns the value of attribute type.



4
5
6
# File 'lib/sinatra/schema/definition.rb', line 4

def type
  @type
end

Instance Method Details

#cast(value) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
# File 'lib/sinatra/schema/definition.rb', line 14

def cast(value)
  # do not touch nulls:
  return unless value

  case type
  when "boolean"
    %w( t true 1 ).include?(value.to_s)
  when "email", "string", "uuid"
    value.to_s
  end
end

#to_schemaObject



41
42
43
44
45
46
47
48
49
50
51
# File 'lib/sinatra/schema/definition.rb', line 41

def to_schema
  schema_type, schema_format = json_schema_type_and_format
  attrs = { type: schema_type }
  if schema_format
    attrs[:format] = schema_format
  end
  if description
    attrs[:description] = description
  end
  attrs
end

#valid?(value) ⇒ Boolean

Returns:

  • (Boolean)


26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/sinatra/schema/definition.rb', line 26

def valid?(value)
  return true if value.nil? && optional

  case type
  when "boolean"
    [true, false].include?(value)
  when "email"
    value.to_s =~ /\A[^@\s]+@([^@\s]+\.)+[^@\s]+\z/
  when "string"
    value.is_a?(String)
  when "uuid"
    value.to_s =~ /\A[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}\Z/
  end
end