Class: Gamefic::Binding
- Inherits:
-
Object
- Object
- Gamefic::Binding
- Defined in:
- lib/gamefic/binding.rb
Overview
A lightweight wrapper around a ‘Proc` that executes it in the context of a specific narrative.
Gamefic stores most author-written blocks (responses, callbacks, etc.) as plain Ruby procs. Those blocks are intended to run within the context of their parent narrative so they can call the narrative’s methods. Gamefic::Binding pairs the proc with its narrative and provides a safe way to execute it.
Instance Attribute Summary collapse
- #code ⇒ Proc readonly
- #narrative ⇒ Narrative readonly
Class Method Summary collapse
-
.for(object) ⇒ Narrative?
Fetch the narrative at the top of an object’s stack.
-
.pop(object) ⇒ Object
Remove a narrative from the top of an object’s stack.
-
.push(object, narrative) ⇒ Object
Push a narrative to the top of an object’s stack.
-
.registry ⇒ Object
A map of objects and the stack of narratives in which they’re currently involved.
Instance Method Summary collapse
-
#call(*args) ⇒ void
(also: #[])
Execute the binding’s code within the context of the narrative.
-
#initialize(narrative, code) ⇒ Binding
constructor
A new instance of Binding.
Constructor Details
#initialize(narrative, code) ⇒ Binding
Returns a new instance of Binding.
56 57 58 59 |
# File 'lib/gamefic/binding.rb', line 56 def initialize(narrative, code) @narrative = narrative @code = code end |
Instance Attribute Details
#code ⇒ Proc (readonly)
52 53 54 |
# File 'lib/gamefic/binding.rb', line 52 def code @code end |
#narrative ⇒ Narrative (readonly)
49 50 51 |
# File 'lib/gamefic/binding.rb', line 49 def narrative @narrative end |
Class Method Details
.for(object) ⇒ Narrative?
Fetch the narrative at the top of an object’s stack.
43 44 45 |
# File 'lib/gamefic/binding.rb', line 43 def for(object) registry.fetch(object, []).last end |
.pop(object) ⇒ Object
Remove a narrative from the top of an object’s stack.
34 35 36 37 |
# File 'lib/gamefic/binding.rb', line 34 def pop(object) registry[object].pop registry.delete(object) if registry[object].empty? end |
.push(object, narrative) ⇒ Object
Push a narrative to the top of an object’s stack.
26 27 28 29 |
# File 'lib/gamefic/binding.rb', line 26 def push(object, narrative) registry[object] ||= [] registry[object].push narrative end |
.registry ⇒ Object
A map of objects and the stack of narratives in which they’re currently involved.
18 19 20 |
# File 'lib/gamefic/binding.rb', line 18 def registry @registry ||= {} end |
Instance Method Details
#call(*args) ⇒ void Also known as: []
This method returns an undefined value.
Execute the binding’s code within the context of the narrative.
64 65 66 67 68 69 |
# File 'lib/gamefic/binding.rb', line 64 def call(*args) args.each { |arg| Binding.push arg, @narrative } @narrative.instance_exec(*args, &@code) ensure args.each { |arg| Binding.pop arg } end |