-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodelspec.rb
116 lines (101 loc) · 2.66 KB
/
modelspec.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#!/bin/ruby
# Data specification
class DataSpec
def initialize file, options={}, &block
# Open file
@file = file.kind_of?(IO) ? file : File.open(file, 'w')
# Print html head
if options[:document]
@file.puts <<-END.gsub(/^[ ]{8}/, '')
<!DOCTYPE html>
<html>
<head>
<title>Model Spec</title>
<meta charset="utf8" />
<style>
td { border: 1px solid black; }
</style>
</head>
<body>
END
end
# Call data specification block on self
self.instance_eval &block
# Print html foot
if options[:document]
@file.puts <<-END.gsub(/^[ ]{8}/, '')
</body>
</html>
END
end
# Close file
@file.close
end
def model name, &block
ModelSpec.new name, @file, &block
end
# Model specification
class ModelSpec
# Attribute after multi index error
class AttrAfterIndexException < Exception
end
def initialize name, file, &block
@file = file
@multiindex = false
# Print table head
@file.puts <<-END.gsub(/^[ ]{8}/, '')
<table>
<tr><td colspan="5"><b>#{name}</b></td></tr>
<tr>
<td><b></b></td>
<td><b>Name</b></td>
<td><b>Constraints</b></td>
<td><b>NULL</b></td>
<td><b>Idx</b></td>
</tr>
END
# Call model specification on self
self.instance_eval &block
# Print table foot
@file.puts "</table>"
end
def attr name, type, options={}
# Assert before multi line
raise AttrAfterIndexException.new if @multiindex
# Apply defaults
options = {
primary: false,
foreign: false,
crts: '',
null: !options[:primary],
index: options[:foreign]
}.merge(options)
# Print table row
@file.puts <<-END.gsub(/^[ ]{6}/, '')
<tr>
<td>#{options[:primary] ? 'PK' : (options[:foreign] ? 'FK' : '')}</td>
<td>#{name} (#{type})</td>
<td>#{options[:crts]}</td>
<td>#{options[:null] ? '✓' : '×'}</td>
<td>#{(options[:index] == :unique) ? 'U' : options[:index] ? '✓' : ''}</td>
</tr>
END
end
def index attrs, options={}
unless @multiindex
@file.puts <<-END.gsub(/^[ ]{8}/, '')
<tr>
<td colspan="5"><b>Multi indices</b></td>
</tr>
END
@multiindex = true
end
@file.puts <<-END.gsub(/^[ ]{6}/, '')
<tr>
<td colspan="4">#{attrs.join(', ')}</td>
<td>#{options[:unique] ? 'U' : '✓'}</td>
</tr>
END
end
end
end