forked from gobuffalo/pop
/
string.go
81 lines (67 loc) · 1.72 KB
/
string.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
package slices
import (
"bytes"
"database/sql/driver"
"encoding/csv"
"encoding/json"
"io"
"strings"
"github.com/lib/pq"
)
// For reading in arrays from postgres
// String is a slice of strings.
type String pq.StringArray
// Interface implements the nulls.nullable interface.
func (s String) Interface() interface{} {
return []string(s)
}
// Scan implements the sql.Scanner interface.
// It allows to read the string slice from the database value.
func (s *String) Scan(src interface{}) error {
ss := pq.StringArray(*s)
err := ss.Scan(src)
*s = String(ss)
return err
}
// Value implements the driver.Valuer interface.
// It allows to convert the string slice to a driver.value.
func (s String) Value() (driver.Value, error) {
ss := pq.StringArray(s)
return ss.Value()
}
// UnmarshalJSON will unmarshall JSON value into
// the string slice representation of this value.
func (s *String) UnmarshalJSON(data []byte) error {
var ss pq.StringArray
if err := json.Unmarshal(data, &ss); err != nil {
return err
}
*s = String(ss)
return nil
}
// UnmarshalText will unmarshall text value into
// the string slice representation of this value.
func (s *String) UnmarshalText(text []byte) error {
r := csv.NewReader(bytes.NewReader(text))
var words []string
for {
record, err := r.Read()
if err == io.EOF {
break
}
if err != nil {
return err
}
words = append(words, record...)
}
*s = String(words)
return nil
}
// TagValue implements the tagValuer interface, to work with https://github.com/gobuffalo/tags.
func (s String) TagValue() string {
return s.Format(",")
}
// Format presents the slice as a string, using a given separator.
func (s String) Format(sep string) string {
return strings.Join([]string(s), sep)
}