/
model_generator.go
91 lines (73 loc) · 1.92 KB
/
model_generator.go
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
package clay
import (
"errors"
"fmt"
"io"
"strings"
"github.com/clipperhouse/typewriter"
)
func init() {
err := typewriter.Register(NewModelGenerator())
if err != nil {
panic(err)
}
}
type ModelGenerator struct{}
func NewModelGenerator() *ModelGenerator {
return &ModelGenerator{}
}
func (g *ModelGenerator) Name() string {
return "model"
}
func (g *ModelGenerator) Imports(t typewriter.Type) []typewriter.ImportSpec {
return []typewriter.ImportSpec{}
}
func (g *ModelGenerator) Write(writer io.Writer, t typewriter.Type) error {
tag, found := t.FindTag(g)
if !found {
return nil
}
// Fetch core template
coreTemplates := templates.Where(func(t *typewriter.Template) bool {
if t != nil && t.Name == "core" {
return true
}
return false
})
if len(coreTemplates) == 0 {
return errors.New("Unable to find 'core' template")
}
coreTemplate, err := coreTemplates[0].Parse()
if err != nil {
return errors.New("Unable to parse 'core' template")
}
// Fetch relation template
relationTemplates := templates.Where(func(t *typewriter.Template) bool {
if t != nil && t.Name == "relation" {
return true
}
return false
})
if len(relationTemplates) == 0 {
return errors.New("Unable to find 'relation' template")
}
relationTemplate, err := relationTemplates[0].Parse()
if err != nil {
return errors.New("Unable to parse 'relation' template")
}
cValues := coreValues{ModelClassName: t.Name}
if err := coreTemplate.Execute(writer, cValues); err != nil {
return err
}
for _, relation := range tag.Values {
templateValues := relationValues{}
templateValues.ModelClassName = t.Name
templateValues.RelationIdentifierName = fmt.Sprintf("%vIdentifier", strings.Title(relation.Name))
templateValues.RelationName = relation.Name
templateValues.RelationClassName = strings.Title(relation.Name)
if err := relationTemplate.Execute(writer, templateValues); err != nil {
return err
}
}
return nil
}