Skip to content

Commit

Permalink
refactor: CachedDecoder -> NewCachedDecoder
Browse files Browse the repository at this point in the history
  • Loading branch information
adhocore committed Nov 19, 2022
1 parent bd5d23f commit 5d4f05f
Show file tree
Hide file tree
Showing 4 changed files with 9 additions and 8 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ import (
)

var dest map[string]interface{}
err := jsonc.CachedDecoder().Decode("./examples/test.json5", &dest);
err := jsonc.NewCachedDecoder().Decode("./examples/test.json5", &dest);
if err != nil {
fmt.Printf("%+v", err)
} else {
Expand Down
11 changes: 6 additions & 5 deletions decode.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,20 @@ import (
"strings"
)

type cachedDecoder struct {
// CachedDecoder is a managed decoder that caches a copy of json5 transitioned to json
type CachedDecoder struct {
jsonc *Jsonc
ext string
}

// CachedDecoder gives a managed decoder that caches a copy of json5 transitioned to json
func CachedDecoder(ext ...string) *cachedDecoder {
// NewCachedDecoder gives a cached decoder
func NewCachedDecoder(ext ...string) *CachedDecoder {
ext = append(ext, ".cached.json")
return &cachedDecoder{New(), ext[0]}
return &CachedDecoder{New(), ext[0]}
}

// Decode decodes from cache if exists and relevant else decodes from source
func (fd *cachedDecoder) Decode(file string, v interface{}) error {
func (fd *CachedDecoder) Decode(file string, v interface{}) error {
stat, err := os.Stat(file)
if err != nil {
return err
Expand Down
2 changes: 1 addition & 1 deletion examples/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ func main() {
j := jsonc.New()

// strip and unmarshal from cached file
if err := jsonc.CachedDecoder().Decode("./examples/test.json5", &v); err != nil {
if err := jsonc.NewCachedDecoder().Decode("./examples/test.json5", &v); err != nil {
fmt.Printf("%#v\n", err)
os.Exit(1)
}
Expand Down
2 changes: 1 addition & 1 deletion jsonc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ func TestUnmarshal(t *testing.T) {

func TestCachedDecoder(t *testing.T) {
file := "./examples/test1.json5"
cd, val := CachedDecoder(), make(map[string]interface{})
cd, val := NewCachedDecoder(), make(map[string]interface{})
t.Run("before cache", func(t *testing.T) {
os.Remove("./examples/test1.cached.json")
if err := cd.Decode(file, &val); err != nil {
Expand Down

0 comments on commit 5d4f05f

Please sign in to comment.