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
25
26
27
28
29
30
# 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 "datetime"
    Time.parse(value.to_s)
  when "email", "string", "uuid"
    value.to_s
  when "integer"
    value.to_i
  when "object"
    value
  end
end

#valid?(value, skip_nils = optional) ⇒ Boolean

Returns:

  • (Boolean)


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/sinatra/schema/definition.rb', line 32

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

  case type
  when "boolean"
    [true, false].include?(value)
  when "datetime"
    value.to_s =~ /^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-2][0-9]:[0-5][0-9]:[0-5][0-9](\.[0-9]+)?(Z|[\-+][0-9]{2}:[0-5][0-9])$/
  when "email"
    value.to_s =~ /\A[^@\s]+@([^@\s]+\.)+[^@\s]+\z/
  when "integer"
    value.to_s =~ /\A\d*\z/
  when "object"
    value.is_a?(Hash)
  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