-
-
Notifications
You must be signed in to change notification settings - Fork 41
/
builder.rb
55 lines (43 loc) · 1.05 KB
/
builder.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
require 'delegate'
require 'rom/factory/struct'
module ROM::Factory
class Builder
attr_reader :schema, :relation
def initialize(schema, relation)
@schema = schema
@relation = relation
@sequence = 0
end
def tuple(attrs)
schema.map {|k, v| [k, v.call] }.to_h.merge(attrs)
end
def create(attrs = {})
struct(tuple(attrs.merge(primary_key => next_id)))
end
def struct(attrs)
Struct.define(relation.name.relation, relation.schema.project(*attrs.keys)).new(attrs)
end
def persistable
Persistable.new(self)
end
def primary_key
relation.primary_key
end
private
def next_id
@sequence += 1
end
end
class Persistable < SimpleDelegator
attr_reader :builder, :relation
def initialize(builder, relation = builder.relation)
super(builder)
@builder = builder
@relation = relation
end
def create(attrs = {})
tuple = builder.tuple(attrs)
struct(tuple.merge(primary_key => relation.insert(tuple)))
end
end
end