Class: RSX::Context
- Inherits:
-
Object
- Object
- RSX::Context
- 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
-
#default ⇒ Object
readonly
Returns the value of attribute default.
-
#name ⇒ Object
readonly
Returns the value of attribute name.
Instance Method Summary collapse
-
#initialize(default = nil, name: nil) ⇒ Context
constructor
A new instance of Context.
- #inspect ⇒ Object
-
#Provider ⇒ Object
(also: #provider)
Allows <Theme.Provider value=...>.
- #value ⇒ Object (also: #current)
- #with(value) ⇒ Object
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
#default ⇒ Object (readonly)
Returns the value of attribute default.
19 20 21 |
# File 'lib/rsx/context.rb', line 19 def default @default end |
#name ⇒ Object (readonly)
Returns the value of attribute name.
19 20 21 |
# File 'lib/rsx/context.rb', line 19 def name @name end |
Instance Method Details
#inspect ⇒ Object
47 48 49 |
# File 'lib/rsx/context.rb', line 47 def inspect "#<RSX::Context #{name || object_id} default=#{@default.inspect}>" end |
#Provider ⇒ Object 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 |
#value ⇒ Object 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 |