PageRenderTime 11ms CodeModel.GetById 2ms app.highlight 6ms RepoModel.GetById 1ms app.codeStats 0ms

/models/preferences.go

http://github.com/TheOnly92/bloody.go
Go | 70 lines | 60 code | 8 blank | 2 comment | 18 complexity | e300273e6d9bf98cbe4ec7cf9a67567b MD5 | raw file
 1package main
 2
 3import (
 4	"launchpad.net/gobson/bson"
 5	"launchpad.net/mgo"
 6)
 7
 8type Preference struct {
 9	Name		string
10	Value		string
11}
12
13type PreferenceModel struct {
14	c			mgo.Collection
15}
16
17func PreferenceInit() *PreferenceModel {
18	p := new(PreferenceModel)
19	p.c = mSession.DB(config.Get("mongodb")).C("preferences")
20	return p
21}
22
23func (preference *PreferenceModel) GetByName(name string) *Preference {
24	var result *Preference
25	err := preference.c.Find(bson.M{"name": name}).One(&result)
26	if err == mgo.NotFound {
27		// See if there's default value
28		value := preference.Get(name)
29		result = &Preference{name, value}
30	} else if err != nil {
31		panic(err)
32	}
33	return result
34}
35
36func (preference *PreferenceModel) Get(name string) string {
37	var result *Preference
38	err := preference.c.Find(bson.M{"name": name}).One(&result)
39	if err == mgo.NotFound {
40		// Default values
41		switch name {
42		case "dateFormat":
43			return "2006 Jan 02 15:04"
44		case "postsPerPage":
45			return "10"
46		case "enableComment":
47			return "on"
48		case "markdown":
49			return "0"
50		}
51	} else if err != nil {
52		panic(err)
53	}
54	
55	return result.Value
56}
57
58func (preference *PreferenceModel) Update(name string, value string) {
59	result := preference.GetByName(name)
60	result.Value = value
61	err := preference.c.Update(bson.M{"name":name},result)
62	if err == mgo.NotFound {
63		err = preference.c.Insert(&Preference{name, value})
64		if err != nil {
65			panic(err)
66		}
67	} else if err != nil {
68		panic(err)
69	}
70}