-
Notifications
You must be signed in to change notification settings - Fork 1
/
relations.rb
100 lines (91 loc) · 2.23 KB
/
relations.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
require 'hash_digger'
require 'hash_remapper'
require 'tapp'
data = {
:books => [
{
:title => "The Hitchhiker's Guide to the Galaxy",
:editions => [
{
:isbn => "978-1-9936-7490-4",
:language => "en",
:pages => 193,
:genres => [
"comic",
"science fiction"
]
},
{
:isbn => "978-0-5762-2634-9",
:language => "en",
:pages => 208,
:genres => [
"comic",
"fiction",
"science fiction"
]
},
{
:isbn => "978-5-4566-1998-3",
:language => "de",
:pages => 232,
:genres => [
"fiction",
"science fiction"
]
}
]
},
{
:title => "To Kill a Mockingbird",
:editions => [
{
:isbn => "978-4-0125-2865-3",
:language => "en",
:pages => 324,
:genres => [
"Southern Gothic",
"Bildungsroman"
]
},
{
:isbn => "978-5-3638-3280-2",
:language => "en",
:pages => 324,
:genres => [
"magic realism"
]
}
]
}
]
}
puts "Here we lose the relations between books and ISBNs:"
raw_result = HashRemapper.remap(
data,
titles: [:titles, { path: 'books.*.title' }],
isbns: [:isbns, { path: 'books.*.editions.*.*.isbn' }]
).tapp
puts '='*50
puts
puts "Here we do a little trick splitting the path into two parts to presev relation in indexes"
isbn_result = HashRemapper.remap(
data,
titles: [:titles, { path: 'books.*.title' }],
isbns: [:isbns, { path: 'books.*.editions.*', lambda: ->(editions) { editions.collect { |edition| HashDigger::Digger.dig(data: edition, path: '*.isbn') } } }]
).tapp
puts '='*50
puts
puts "Then we zip the data together in key => value format:"
Hash[isbn_result[:titles].zip(isbn_result[:isbns])].tapp
puts '='*50
puts ''
puts "Or create the new hashes assebling the data in any desirable structure:"
books_with_isbns = []
isbn_result[:titles].each_with_index do |t, i|
books_with_isbns << {
title: t,
isbns: isbn_result[:isbns][i].uniq
}
end
books_with_isbns.tapp