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

TextMarshaler #24

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
18 changes: 18 additions & 0 deletions dump_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -949,3 +949,21 @@ TT.DY: d
`
assert.Equal(t, expected, out.String())
}

type TextMarshal string

func (t TextMarshal) MarshallText() (string, error) {
return "'" + string(t) + "'", nil
}

func (t TextMarshal) Type() string {
return "MyType"
}

func TestImplementsInterface(t *testing.T) {
out := &bytes.Buffer{}

require.NoError(t, dump.NewEncoder(out).Fdump(TextMarshal("foo")))

assert.Equal(t, ": 'foo'\n", out.String())
}
30 changes: 26 additions & 4 deletions encoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@ type Encoder struct {
writer io.Writer
}

type TextMarshaler interface {
MarshallText() (string, error)
Type() string
}

// NewDefaultEncoder instanciate a go-dump encoder
func NewDefaultEncoder() *Encoder {
return NewEncoder(new(bytes.Buffer))
Expand Down Expand Up @@ -106,8 +111,25 @@ func (e *Encoder) fdumpInterface(w map[string]interface{}, i interface{}, roots
w[prefix+k] = ""
return nil
}
switch f.Kind() {
case reflect.Struct:

marshaler, convertible := i.(TextMarshaler)

switch {
case convertible:
value, err := marshaler.MarshallText()
if err != nil {
return err
}

if e.ExtraFields.Type {
nodeType := append(roots, "__Type__")
nodeTypeFormatted := strings.Join(sliceFormat(nodeType, e.Formatters), e.Separator)
w[nodeTypeFormatted] = marshaler.Type()
}

return e.fdumpInterface(w, value, roots)

case f.Kind() == reflect.Struct:
if e.ExtraFields.Type {
nodeType := append(roots, "__Type__")
nodeTypeFormatted := strings.Join(sliceFormat(nodeType, e.Formatters), e.Separator)
Expand All @@ -120,12 +142,12 @@ func (e *Encoder) fdumpInterface(w map[string]interface{}, i interface{}, roots
if err := e.fdumpStruct(w, f, croots); err != nil {
return err
}
case reflect.Array, reflect.Slice:
case f.Kind() == reflect.Array, f.Kind() == reflect.Slice:
if err := e.fDumpArray(w, i, roots); err != nil {
return err
}
return nil
case reflect.Map:
case f.Kind() == reflect.Map:
if e.ExtraFields.Type {
nodeType := append(roots, "__Type__")
nodeTypeFormatted := strings.Join(sliceFormat(nodeType, e.Formatters), e.Separator)
Expand Down