This repository was archived by the owner on Feb 13, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdenormalization_with_maps.rb
More file actions
102 lines (83 loc) · 2.03 KB
/
denormalization_with_maps.rb
File metadata and controls
102 lines (83 loc) · 2.03 KB
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
101
102
require_relative "activerecord_setup"
ActiveRecord::Schema.define do
create_table :foos, force: true do |t|
t.jsonb :bar_links
t.jsonb :bin_link
t.timestamps
end
create_table :bars, force: true do |t|
t.timestamps
end
create_table :bins, force: true do |t|
t.timestamps
end
end
module DenormalizedAssociations
def denormalized_has_many(associated_table_name)
define_method associated_table_name do
associated_table_name.
to_s.
classify.
constantize.
where(id: send("#{associated_table_name.to_s.singularize}_links").keys)
end
define_method "#{associated_table_name.to_s.singularize}_ids" do
send("#{associated_table_name.to_s.singularize}_links").keys.map(&:to_i)
end
end
def denormalized_belongs_to(associated_instance_name)
define_method associated_instance_name do
associated_instance_name.
to_s.
classify.
constantize.
find(send("#{associated_instance_name}_link").keys.first.to_i)
end
define_method "#{associated_instance_name.to_s.singularize}_id" do
send("#{associated_instance_name}_link").keys.first.to_i
end
end
end
class ActiveRecord::Base
extend DenormalizedAssociations
end
class Foo < ActiveRecord::Base
denormalized_has_many :bars
denormalized_belongs_to :bin
end
class Bar < ActiveRecord::Base
end
class Bin < ActiveRecord::Base
end
class DenormalizationTest < Minitest::Test
def setup
Foo.destroy_all
Bar.destroy_all
Bin.destroy_all
end
def test_has_many
5.times do
Bar.create
end
foo = Foo.create(
bar_links: {
"1" => { "fruit" => "banana" },
"2" => { "fruit" => "orange" }
}
)
assert_equal(foo.bars.map(&:id), [1, 2])
assert_equal(foo.bar_ids, [1, 2])
end
def test_belongs_to
5.times do
Bin.create
end
foo = Foo.create(
bin_link: {
"2" => { "vegetable" => "carrot" },
}
)
assert_equal(foo.bin, Bin.find(2))
assert_equal(foo.bin_id, 2)
end
end