Class: AboutYml::DataFaker

Inherits:
Object
  • Object
show all
Defined in:
lib/about_yml/data_faker.rb

Constant Summary collapse

TYPE_MAP =
{
  'string' => lambda { Random.alphanumeric },
  'boolean' => lambda { Random.boolean },
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeDataFaker

Returns a new instance of DataFaker.



16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/about_yml/data_faker.rb', line 16

def initialize
  @generator = AboutYml::TemplateGenerator.new
  template = @generator.generate
  @template_data = YAML.load template

  # load up the JSON schema to fill in appropriate values
  schema = AboutYml::AboutFile.schema

  @template_data.collect do |k, _|
    @template_data[k] = fill_data schema['properties'][k]
  end
end

Instance Attribute Details

#template_dataObject (readonly)

Returns the value of attribute template_data.



9
10
11
# File 'lib/about_yml/data_faker.rb', line 9

def template_data
  @template_data
end

Instance Method Details

#fill_array(props) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/about_yml/data_faker.rb', line 42

def fill_array(props)
  subtype = props['items']['type']

  3.times.collect do
    if TYPE_MAP[subtype]
      TYPE_MAP[subtype].call
    else
      subprops = @generator.definition_properties props['items']['$ref']
      fill_new_object subprops
    end
  end
end

#fill_data(props) ⇒ Object

populate the template with random values according to their type in the schema



31
32
33
34
35
36
37
38
39
40
# File 'lib/about_yml/data_faker.rb', line 31

def fill_data(props)
  return unless props.key? 'type'
  type = props['type']

  return props['enum'].rand if props.key? 'enum'
  return fill_array props   if type == 'array'
  return fill_object props  if type == 'object'

  TYPE_MAP[type].call if TYPE_MAP[type]
end

#fill_new_object(props) ⇒ Object



71
72
73
74
75
# File 'lib/about_yml/data_faker.rb', line 71

def fill_new_object(props)
  new_obj = {}
  props.map { |k, _| new_obj[k] = fill_data props[k] }
  new_obj
end

#fill_object(props) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/about_yml/data_faker.rb', line 55

def fill_object(props)
  if props.key? 'items'
    return fill_data @generator.definition_properties props['items']['$ref']
  elsif props.key? 'patternProperties'
    # this is hacky, but will work unless the "licenses" patternProperties
    # are changed to include more than one pattern
    _, v = props['patternProperties'].shift
    subprops = @generator.definition_properties v['$ref']

    # the patternProperties works by regex matching on the keys of the
    # sub-object, # so we need to create another level of nesting with
    # a random key
    return { Random.alphanumeric => fill_new_object(subprops) }
  end
end