Added MemoryLoader and test.
This commit is contained in:
parent
3ccaaf6dc4
commit
cf92aa26df
21
loader.go
21
loader.go
|
@ -14,15 +14,16 @@ type Loader interface {
|
|||
}
|
||||
|
||||
type stringTemplate struct {
|
||||
name string
|
||||
contents string
|
||||
}
|
||||
|
||||
func (t *stringTemplate) Name() string {
|
||||
return t.contents
|
||||
return t.name
|
||||
}
|
||||
|
||||
func (t *stringTemplate) Contents() io.Reader {
|
||||
return bytes.NewReader([]byte(t.contents))
|
||||
return bytes.NewBufferString(t.contents)
|
||||
}
|
||||
|
||||
// StringLoader is intended to be used to load Stick templates directly from a string.
|
||||
|
@ -30,7 +31,21 @@ type StringLoader struct{}
|
|||
|
||||
// Load on a StringLoader simply returns the name that is passed in.
|
||||
func (l *StringLoader) Load(name string) (Template, error) {
|
||||
return &stringTemplate{name}, nil
|
||||
return &stringTemplate{name, name}, nil
|
||||
}
|
||||
|
||||
// MemoryLoader loads templates from an in-memory map.
|
||||
type MemoryLoader struct {
|
||||
Templates map[string]string
|
||||
}
|
||||
|
||||
// Load tries to load the template from the in-memory map.
|
||||
func (l *MemoryLoader) Load(name string) (Template, error) {
|
||||
v, ok := l.Templates[name]
|
||||
if !ok {
|
||||
return nil, os.ErrNotExist
|
||||
}
|
||||
return &stringTemplate{name, v}, nil
|
||||
}
|
||||
|
||||
type fileTemplate struct {
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
package stick
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
@ -32,3 +33,20 @@ func TestStringLoader(t *testing.T) {
|
|||
t.Errorf("unexpected template name: %s", b.Name())
|
||||
}
|
||||
}
|
||||
|
||||
func TestMemoryLoader(t *testing.T) {
|
||||
l := &MemoryLoader{map[string]string{"test.twig": "some text"}}
|
||||
b, e := l.Load("test.twig")
|
||||
if e != nil {
|
||||
t.Fatalf("expected load to succeed got %s", e)
|
||||
} else if b.Name() != "test.twig" {
|
||||
t.Fatalf("expected to load test.twig got %s", b.Name())
|
||||
}
|
||||
s, e := ioutil.ReadAll(b.Contents())
|
||||
if e != nil {
|
||||
t.Fatalf("unexpected error %s", e)
|
||||
}
|
||||
if string(s) != "some text" {
|
||||
t.Fatalf("expected 'some text' got '%s'", string(s))
|
||||
}
|
||||
}
|
||||
|
|
Reference in a new issue