This repository has been archived by the owner on Dec 9, 2020. It is now read-only.
forked from gobuffalo/plush
-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.go
99 lines (85 loc) · 2.1 KB
/
context.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package plush
import (
"context"
"sync"
"github.com/gobuffalo/helpers/hctx"
)
var _ context.Context = &Context{}
// Context holds all of the data for the template that is being rendered.
type Context struct {
context.Context
data map[string]interface{}
outer *Context
moot *sync.Mutex
}
// New context containing the current context. Values set on the new context
// will not be set onto the original context, however, the original context's
// values will be available to the new context.
func (c *Context) New() hctx.Context {
cc := NewContext()
cc.outer = c
return cc
}
// Set a value onto the context
func (c *Context) Set(key string, value interface{}) {
c.moot.Lock()
defer c.moot.Unlock()
c.data[key] = value
}
// Value from the context, or it's parent's context if one exists.
func (c *Context) Value(key interface{}) interface{} {
if s, ok := key.(string); ok {
if v, ok := c.data[s]; ok {
return v
}
if c.outer != nil {
return c.outer.Value(s)
}
}
return c.Context.Value(key)
}
// Has checks the existence of the key in the context.
func (c *Context) Has(key string) bool {
return c.Value(key) != nil
}
// Export all the known values in the context.
// Note this can't reach up into other implemenations
// of context.Context.
func (c *Context) export() map[string]interface{} {
m := map[string]interface{}{}
if c.outer != nil {
for k, v := range c.outer.export() {
m[k] = v
}
}
for k, v := range c.data {
m[k] = v
}
return m
}
// NewContext returns a fully formed context ready to go
func NewContext() *Context {
return NewContextWith(map[string]interface{}{})
}
// NewContextWith returns a fully formed context using the data
// provided.
func NewContextWith(data map[string]interface{}) *Context {
c := &Context{
Context: context.Background(),
data: data,
outer: nil,
moot: &sync.Mutex{},
}
for k, v := range Helpers.helpers {
if !c.Has(k) {
c.Set(k, v)
}
}
return c
}
// NewContextWithContext returns a new plush.Context given another context
func NewContextWithContext(ctx context.Context) *Context {
c := NewContext()
c.Context = ctx
return c
}