forked from ungerik/go-start
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dynamicchoice.go
88 lines (73 loc) · 1.77 KB
/
dynamicchoice.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
package model
import (
"fmt"
"labix.org/v2/mgo/bson"
)
///////////////////////////////////////////////////////////////////////////////
// DynamicChoice
type DynamicChoice struct {
index int
options []string
}
func (self *DynamicChoice) Index() int {
return self.index
}
func (self *DynamicChoice) SetIndex(index int) error {
err := self.CheckIndex(index)
if err == nil {
self.index = index
}
return err
}
func (self *DynamicChoice) Options() []string {
return self.options
}
func (self *DynamicChoice) SetOptions(options []string) {
self.options = options
}
func (self *DynamicChoice) String() string {
if self.index < 0 || self.index >= len(self.options) {
return ""
}
return self.options[self.index]
}
func (self *DynamicChoice) SetString(str string) error {
for i, option := range self.options {
if str == option {
self.index = i
return nil
}
}
// Temporary Hot Fix
return nil
// return &InvalidChoice{str, self.options}
}
func (self *DynamicChoice) GetBSON() (interface{}, error) {
return self.String(), nil
}
func (self *DynamicChoice) SetBSON(raw bson.Raw) (err error) {
var s string
err = raw.Unmarshal(&s)
if err != nil {
return err
}
return self.SetString(s)
}
func (self *DynamicChoice) IsEmpty() bool {
return self.String() == ""
}
func (self *DynamicChoice) Required(metaData *MetaData) bool {
return len(self.options) > 0 && self.options[0] != ""
}
func (self *DynamicChoice) Validate(metaData *MetaData) error {
if self.Required(metaData) && self.IsEmpty() {
return NewRequiredError(metaData)
}
return self.CheckIndex(self.index)
}
func (self *DynamicChoice) CheckIndex(index int) error {
if index < 0 || index >= len(self.options) {
return fmt.Errorf("Choice index %d out of range [0..%d)", index, len(self.options))
}
return nil
}