Skip to content

Instantly share code, notes, and snippets.

@mattes
Last active August 29, 2015 14:16
Show Gist options
  • Save mattes/e24ed9e87822ded76604 to your computer and use it in GitHub Desktop.
Save mattes/e24ed9e87822ded76604 to your computer and use it in GitHub Desktop.
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)
}
@brendensoares
Copy link

Product shouldn't need to provide implementations of Save() and Find(). Each model should simply define its attributes. The process of adapting/marshaling the model's struct from Go to SQL is done by the Model 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment