common/maps: Add Scratch.Values
authorBjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>
Fri, 29 May 2020 16:50:12 +0000 (18:50 +0200)
committerBjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>
Fri, 29 May 2020 17:51:49 +0000 (19:51 +0200)
Fixes #7335

common/maps/scratch.go
common/maps/scratch_test.go
docs/content/en/functions/scratch.md

index 4acd10c6cb2ed3b8055f6436d703d91883332c6a..7a3cd37485c814a4bfc7a8e79aa069d255c5ff65 100644 (file)
@@ -107,6 +107,15 @@ func (c *Scratch) Get(key string) interface{} {
        return val
 }
 
+// Values returns the raw backing map. Note that you should just use
+// this method on the locally scoped Scratch instances you obtain via newScratch, not
+// .Page.Scratch etc., as that will lead to concurrency issues.
+func (c *Scratch) Values() map[string]interface{} {
+       c.mu.RLock()
+       defer c.mu.RUnlock()
+       return c.values
+}
+
 // SetInMap stores a value to a map with the given key in the Node context.
 // This map can later be retrieved with GetSortedMapValues.
 func (c *Scratch) SetInMap(key string, mapKey string, value interface{}) string {
@@ -147,7 +156,7 @@ func (c *Scratch) GetSortedMapValues(key string) interface{} {
        return sortedArray
 }
 
-// NewScratch returns a new instance Scratch.
+// NewScratch returns a new instance of Scratch.
 func NewScratch() *Scratch {
        return &Scratch{values: make(map[string]interface{})}
 }
index c2c436e403c13abb645873c360febe2442427563..40df3bb6be2b46a5b9ec7f26b544d7e87d2f7574 100644 (file)
@@ -47,6 +47,9 @@ func TestScratchAdd(t *testing.T) {
        scratch.Add("scratch", scratch)
        _, err := scratch.Add("scratch", scratch)
 
+       m := scratch.Values()
+       c.Assert(m, qt.HasLen, 5)
+
        if err == nil {
                t.Errorf("Expected error from invalid arithmetic")
        }
index 1a64bb2e33611d3b0a63e752d3e46f6bf29cdd21..10623b2cb3a1da3eec35baaba18aa066f7f2182a 100644 (file)
@@ -113,6 +113,11 @@ Removes the given key
 {{ .Scratch.Delete "greetings" }}
 ```
 
+#### .Values
+
+`Values` returns the raw backing map. Note that you should just use this method on the locally scoped `Scratch` instances you obtain via `newScratch`, not
+ `.Page.Scratch` etc., as that will lead to concurrency issues.
+
 ## Scope
 The scope of the backing data is global for the given `Page` or `Shortcode`, and spans partial and shortcode includes.