Class: RSX::Context

Inherits:
Object
  • Object
show all
Defined in:
lib/rsx/context.rb

Overview

React's Context API: a value provided high in the tree and read anywhere below it without threading props through every component in between.

Theme = RSX.create_context("light")

<Theme.Provider value={"dark"}>
<Toolbar />
</Theme.Provider>

# inside any descendant
{use_context(Theme)}

Provided values live on a per-thread stack, so concurrent requests never see each other's context.

Defined Under Namespace

Classes: ProviderComponent

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(default = nil, name: nil) ⇒ Context

Returns a new instance of Context.



21
22
23
24
25
# File 'lib/rsx/context.rb', line 21

def initialize(default = nil, name: nil)
  @default = default
  @name = name
  @key = :"rsx_context_#{object_id}"
end

Instance Attribute Details

#defaultObject (readonly)

Returns the value of attribute default.



19
20
21
# File 'lib/rsx/context.rb', line 19

def default
  @default
end

#nameObject (readonly)

Returns the value of attribute name.



19
20
21
# File 'lib/rsx/context.rb', line 19

def name
  @name
end

Instance Method Details

#inspectObject



47
48
49
# File 'lib/rsx/context.rb', line 47

def inspect
  "#<RSX::Context #{name || object_id} default=#{@default.inspect}>"
end

#ProviderObject Also known as: provider

Allows <Theme.Provider value=...>



42
43
44
# File 'lib/rsx/context.rb', line 42

def Provider # rubocop:disable Naming/MethodName
  @provider ||= ProviderComponent.new(self)
end

#valueObject Also known as: current



27
28
29
30
# File 'lib/rsx/context.rb', line 27

def value
  stack = Thread.current[@key]
  stack && !stack.empty? ? stack.last : @default
end

#with(value) ⇒ Object



33
34
35
36
37
38
39
# File 'lib/rsx/context.rb', line 33

def with(value)
  stack = (Thread.current[@key] ||= [])
  stack.push(value)
  yield
ensure
  stack.pop
end