Class: Screiji::Root

Inherits:
Object
  • Object
show all
Defined in:
lib/screiji/root.rb

Instance Method Summary collapse

Constructor Details

#initialize(schema) ⇒ Root

Returns a new instance of Root.



5
6
7
8
# File 'lib/screiji/root.rb', line 5

def initialize(schema)
  schema = JSON.parse(File.read(schema)) if schema.is_a? String
  @schema = schema
end

Instance Method Details

#example(schema) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/screiji/root.rb', line 43

def example(schema)
  case schema['type']
  when 'boolean'
    [true, false].sample
  when 'integer'
    Random.rand(1 .. 1000)
  when 'number'
    Random.rand(-1000 .. 1000)
  when 'null'
    nil
  when 'string'
    rand(36**5).to_s(36)
  else
    raise "cant generate example for Array and Object"
  end
end

#parse(schema) ⇒ Object



14
15
16
17
18
19
20
21
22
23
# File 'lib/screiji/root.rb', line 14

def parse(schema)
  case schema['type']
  when 'object'
    parse_object(schema)
  when 'array'
    parse_array(schema)
  else
    schema.has_key?('example') ? schema['example'] : example(schema)
  end
end

#parse_array(schema) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
# File 'lib/screiji/root.rb', line 31

def parse_array(schema)
  if schema['items'].is_a? Array
    schema['items'].map do |item|
      parse(item)
    end
  elsif schema['items'].is_a? Hash
    [parse(schema['items'])]
  else
    raise '`items` can include Array or Hash.'
  end
end

#parse_object(schema) ⇒ Object



25
26
27
28
29
# File 'lib/screiji/root.rb', line 25

def parse_object(schema)
  Hash[schema['properties'].map {|k, v|
    [k, parse(v)]
  }]
end

#to_schemaObject



10
11
12
# File 'lib/screiji/root.rb', line 10

def to_schema
  parse(@schema)
end