Class: Gamefic::Binding

Inherits:
Object
  • Object
show all
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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(narrative, code) ⇒ Binding

Returns a new instance of Binding.

Parameters:



56
57
58
59
# File 'lib/gamefic/binding.rb', line 56

def initialize(narrative, code)
  @narrative = narrative
  @code = code
end

Instance Attribute Details

#codeProc (readonly)

Returns:

  • (Proc)


52
53
54
# File 'lib/gamefic/binding.rb', line 52

def code
  @code
end

#narrativeNarrative (readonly)

Returns:



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.

Parameters:

  • object (Object)

Returns:



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.

Parameters:

  • object (Object)


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.

Parameters:



26
27
28
29
# File 'lib/gamefic/binding.rb', line 26

def push(object, narrative)
  registry[object] ||= []
  registry[object].push narrative
end

.registryObject

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