forked from faker-ruby/faker
/
json.rb
70 lines (60 loc) · 1.91 KB
/
json.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
module Faker
class Json < Base
require 'json'
class << self
def shallow_json(width = 3, options = { key: 'Name.first_name', value: 'Name.first_name' })
options[:key] = 'Faker::' + options[:key]
options[:value] = 'Faker::' + options[:value]
hash = build_shallow_hash(width, options)
JSON.generate(hash)
end
def add_depth_to_json(json = shallow_json, width = 3, options = { key: 'Name.first_name', value: 'Name.first_name' })
options[:key] = 'Faker::' + options[:key]
options[:value] = 'Faker::' + options[:value]
hash = JSON.parse(json)
hash.each do |key, _|
add_hash_to_bottom(hash, [key], width, options)
end
JSON.generate(hash)
end
private
def build_shallow_hash(width, options)
key = options[:key]
value = options[:value]
hash = {}
width.times do
hash[eval(key)] = eval(value)
end
hash
end
def add_hash_to_bottom(hash, key_array, width, options)
key_string = build_keys_from_array(key_array)
if eval("hash#{key_string}").is_a?(::Hash)
eval("hash#{key_string}").each do |key, _|
key_array << key
add_hash_to_bottom(hash, key_array, width, options)
end
else
add_hash(key_array, hash, width, options)
key_array.pop
end
end
def add_hash(key_array, hash, width, options)
string_to_eval = 'hash'
key_array.length.times do |index|
string_to_eval << "['#{key_array[index]}']"
end
string_to_eval << " = #{build_shallow_hash(width, options)}"
eval(string_to_eval)
hash
end
def build_keys_from_array(key_array)
key_string = ''
key_array.each do |value|
key_string << "['#{value}']"
end
key_string
end
end
end
end