move some stuff

This commit is contained in:
Henrique Dias
2016-10-22 12:07:19 +01:00
parent df888b604a
commit 5fce287cd2
10 changed files with 45 additions and 44 deletions

13
utils/variables/types.go Normal file
View File

@@ -0,0 +1,13 @@
package variables
import "reflect"
// IsMap checks if some variable is a map
func IsMap(sth interface{}) bool {
return reflect.ValueOf(sth).Kind() == reflect.Map
}
// IsSlice checks if some variable is a slice
func IsSlice(sth interface{}) bool {
return reflect.ValueOf(sth).Kind() == reflect.Slice
}

View File

@@ -0,0 +1,47 @@
package variables
import (
"errors"
"log"
"reflect"
)
// Defined checks if variable is defined in a struct
func Defined(data interface{}, field string) bool {
t := reflect.Indirect(reflect.ValueOf(data)).Type()
if t.Kind() != reflect.Struct {
log.Print("Non-struct type not allowed.")
return false
}
_, b := t.FieldByName(field)
return b
}
// Dict allows to send more than one variable into a template
func Dict(values ...interface{}) (map[string]interface{}, error) {
if len(values)%2 != 0 {
return nil, errors.New("invalid dict call")
}
dict := make(map[string]interface{}, len(values)/2)
for i := 0; i < len(values); i += 2 {
key, ok := values[i].(string)
if !ok {
return nil, errors.New("dict keys must be strings")
}
dict[key] = values[i+1]
}
return dict, nil
}
// StringInSlice checks if a slice contains a string
func StringInSlice(a string, list []string) (bool, int) {
for i, b := range list {
if b == a {
return true, i
}
}
return false, 0
}

View File

@@ -0,0 +1,41 @@
package variables
import "testing"
type testDefinedData struct {
f1 string
f2 bool
f3 int
f4 func()
}
type testDefined struct {
data interface{}
field string
result bool
}
var testDefinedCases = []testDefined{
{testDefinedData{}, "f1", true},
{testDefinedData{}, "f2", true},
{testDefinedData{}, "f3", true},
{testDefinedData{}, "f4", true},
{testDefinedData{}, "f5", false},
{[]string{}, "", false},
{map[string]int{"oi": 4}, "", false},
{"asa", "", false},
{"int", "", false},
}
func TestDefined(t *testing.T) {
for _, pair := range testDefinedCases {
v := Defined(pair.data, pair.field)
if v != pair.result {
t.Error(
"For", pair.data,
"expected", pair.result,
"got", v,
)
}
}
}