Skip to content

Commit

Permalink
add Stringer
Browse files Browse the repository at this point in the history
  • Loading branch information
linkdata committed Nov 20, 2024
1 parent d2dc188 commit 7d5d424
Show file tree
Hide file tree
Showing 6 changed files with 67 additions and 5 deletions.
2 changes: 1 addition & 1 deletion htmlgetter.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ func makeHtmlGetter(v any) HtmlGetter {
return atomicSetter{v}
case template.HTML:
return htmlGetter{v}
case Stringer:
case stringer:
return htmlStringGetter{stringerGetter{v}}
case string:
h := template.HTML(v) // #nosec G203
Expand Down
19 changes: 18 additions & 1 deletion stringer.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,22 @@
package jaws

type Stringer interface {
import "fmt"

type stringer interface {
String() string
}

type stringizer struct {
v *any
}

func (s stringizer) String() string {
if s.v == nil {
return "<nil>"
}
return fmt.Sprint(*s.v)
}

func Stringer(v *any) stringer {
return stringizer{v}
}
45 changes: 45 additions & 0 deletions stringer_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package jaws

import (
"reflect"
"testing"
)

func TestStringer(t *testing.T) {
var pnil any
txt := any("text")
num := any(int(123))
tests := []struct {
name string
arg *any
want string
}{
{
name: "nil",
arg: nil,
want: "<nil>",
},
{
name: "pointer to nil",
arg: &pnil,
want: "<nil>",
},
{
name: "text",
arg: &txt,
want: "text",
},
{
name: "num",
arg: &num,
want: "123",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := Stringer(tt.arg).String(); !reflect.DeepEqual(got, tt.want) {
t.Errorf("Stringer() = %v, want %v", got, tt.want)
}
})
}
}
2 changes: 1 addition & 1 deletion stringergetter.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package jaws

type stringerGetter struct{ v Stringer }
type stringerGetter struct{ v stringer }

func (g stringerGetter) JawsGetString(e *Element) string {
return g.v.String()
Expand Down
2 changes: 1 addition & 1 deletion stringgetter.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ func makeStringGetter(v any) StringGetter {
return stringGetter{string(v)}
case template.HTMLAttr:
return stringGetter{string(v)}
case Stringer:
case stringer:
return stringerGetter{v}
}
panic(fmt.Errorf("expected jaws.StringGetter or string, not %T", v))
Expand Down
2 changes: 1 addition & 1 deletion stringsetter.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ func makeStringSetter(v any) StringSetter {
return stringSetterT{v}
case Getter[string]:
return stringGetterT{v}
case Stringer:
case stringer:
return stringerGetter{v}
case string:
return stringGetter{v}
Expand Down

0 comments on commit 7d5d424

Please sign in to comment.