From 11b4ae49ca5630c6be774b335c06c2c08cf045c2 Mon Sep 17 00:00:00 2001 From: Eduard Urbach Date: Thu, 6 Jul 2023 15:02:50 +0200 Subject: [PATCH] Added type inference --- Collection.go | 3 +++ Collection_test.go | 6 +++--- README.md | 10 +++++----- 3 files changed, 11 insertions(+), 8 deletions(-) diff --git a/Collection.go b/Collection.go index 6e497db..8271d33 100644 --- a/Collection.go +++ b/Collection.go @@ -4,6 +4,7 @@ import ( "encoding/json" "os" "path/filepath" + "reflect" "strings" "sync" ) @@ -26,6 +27,7 @@ type collection[T any] struct { // New creates a new collection with the given name. func New[T any](directories ...string) (*collection[T], error) { + name := reflect.TypeOf(*new(T)).Name() home, err := os.UserHomeDir() if err != nil { @@ -33,6 +35,7 @@ func New[T any](directories ...string) (*collection[T], error) { } directories = append([]string{home, ".ocean"}, directories...) + directories = append(directories, name) directory := filepath.Join(directories...) err = os.MkdirAll(directory, 0700) diff --git a/Collection_test.go b/Collection_test.go index 16f8e8b..3e1637a 100644 --- a/Collection_test.go +++ b/Collection_test.go @@ -12,7 +12,7 @@ type User struct { } func TestCollectionGet(t *testing.T) { - users, err := ocean.New[User]("test", "User") + users, err := ocean.New[User]("test") assert.Nil(t, err) defer users.Clear() @@ -24,7 +24,7 @@ func TestCollectionGet(t *testing.T) { } func TestInteraction(t *testing.T) { - users, err := ocean.New[User]("test", "User") + users, err := ocean.New[User]("test") assert.Nil(t, err) defer users.Clear() @@ -53,7 +53,7 @@ func TestInteraction(t *testing.T) { } func TestCollectionAll(t *testing.T) { - users, err := ocean.New[User]("test", "User") + users, err := ocean.New[User]("test") assert.Nil(t, err) defer users.Clear() diff --git a/README.md b/README.md index 88889fb..fd07c24 100644 --- a/README.md +++ b/README.md @@ -20,13 +20,13 @@ type User struct { Name string } -// Data saved to ~/.ocean/User/ -users := ocean.New[User]("User") +// Load existing data from ~/.ocean/User/ +users := ocean.New[User]() -// Store key and value in memory and write ~/.ocean/User/1.json +// Store in memory and also store in ~/.ocean/User/1.json users.Set("1", &User{Name: "User 1"}) -// Read value from memory +// Read from memory user, err := users.Get("1") ``` @@ -34,7 +34,7 @@ In a real project you would usually prefix your collections with a project or co ```go // Data saved to ~/.ocean/google/User/ -users := ocean.New[User]("google", "User") +users := ocean.New[User]("google") ``` ## Recommended structure