Last active
August 29, 2015 14:16
-
-
Save mattes/e24ed9e87822ded76604 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"github.com/davecgh/go-spew/spew" | |
"reflect" | |
) | |
type Model struct { | |
Dirty bool | |
Error error | |
} | |
func SaveFunc(i interface{}) interface{} { | |
meta := reflect.ValueOf(i).Elem().FieldByName("Meta") | |
meta.FieldByName("Dirty").SetBool(true) | |
return i | |
} | |
func (m *Model) Chain() *Model { | |
if m.Error { | |
return m | |
} else { | |
// do sth | |
} | |
} | |
func FindFunc(i interface{}, id interface{}) (interface{}, error) { | |
switch id.(type) { | |
case int: | |
if id.(int) == 1 { | |
reflect.ValueOf(i).Elem().FieldByName("Name").SetString("Bob") | |
} | |
} | |
return i | |
} | |
type Product struct { | |
Meta Model | |
Name string | |
} | |
func (m *Product) Save() *Product { | |
return SaveFunc(m).(*Product) | |
} | |
func (m *Product) Find(id interface{}) (*Product, error) { | |
return FindFunc(m, id).(*Product) | |
} | |
func main() { | |
p := &Product{} | |
p.Name = "peter" | |
p.Save() | |
spew.Dump(p) | |
p2 := (&Product{}).Chain().Find("1") | |
spew.Dump(p2) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Product
shouldn't need to provide implementations ofSave()
andFind()
. Each model should simply define its attributes. The process of adapting/marshaling the model'sstruct
from Go to SQL is done by theModel
driver implementation. We can chat more soon to consider some examples. Maybe this Saturday at 11pm GMT-8 which is Sunday at 8am GMT+1.