Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add data.Marshaler #19

Merged
merged 1 commit into from
Jan 18, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions data/convert.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,11 @@ func NewWith(convert StructOptions, value interface{}) Value {
return Null{}
}

// see if value implements MarshalValue
if mar, ok := value.(Marshaler); ok {
return mar.MarshalValue()
}

// drill through pointers and interfaces to the underlying type
var v = reflect.ValueOf(value)
for v.Kind() == reflect.Interface || v.Kind() == reflect.Ptr {
Expand Down Expand Up @@ -103,3 +108,9 @@ func (c StructOptions) Data(obj interface{}) Map {
}
return Map(m)
}

// Marshaler is the interface implemented by entities that can marshal
// themselves into a data.Value.
type Marshaler interface {
MarshalValue() Value
}
18 changes: 18 additions & 0 deletions data/convert_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,10 @@ func TestNew(t *testing.T) {
PI *AInt
}{{nil}},
List{Map{"pI": Null{}}}},
{testIDURL{1, "https://github.com/robfig/soy"},
Map{"iD": Int(1), "uRL": String("https://github.com/robfig/soy")}},
{testIDURLMarshaler{1, "https://github.com/robfig/soy"},
Map{"id": Int(1), "url": String("https://github.com/robfig/soy")}},
}

for _, test := range tests {
Expand All @@ -60,6 +64,20 @@ func TestNew(t *testing.T) {
}
}

type testIDURL struct {
ID int
URL string
}

type testIDURLMarshaler testIDURL

func (t testIDURLMarshaler) MarshalValue() Value {
return Map{
"id": New(t.ID),
"url": New(t.URL),
}
}

func TestStructOptions(t *testing.T) {
var testStruct = struct {
CaseFormat int
Expand Down