Module: Gamefic::Scriptable

Included in:
Plot, Subplot
Defined in:
lib/gamefic/scriptable.rb

Overview

The Scriptable module provides a clean room (aka “theater”) for scripts.

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(klass) ⇒ Object



53
54
55
# File 'lib/gamefic/scriptable.rb', line 53

def self.included klass
  klass.extend ClassMethods
end

Instance Method Details

#stage(*args, &block) ⇒ Object

Execute a block of code in a subset of the owner’s scope.

The provided code is evaluated inside a clean room object that has its own instance variables and access to the owner’s public methods. The proc can accept the method call’s arguments.

Examples:

Execute a block of code

stage {
  puts 'Hello'
}

Execute a block of code with arguments

stage 'hello' { |message|
  puts message # <- prints 'hello'
}

Use an instance variable

stage { @message = 'hello'" }
stage { puts @message } # <- prints 'hello'


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
# File 'lib/gamefic/scriptable.rb', line 33

module Scriptable
  module ClassMethods
    # An array of blocks that were added by the `script` class method.

    #

    # @return [Array<Proc>]

    def blocks
      @blocks ||= []
    end

    # Add a block to be executed by the instance's `stage` method.

    #

    # Note that `script` does not execute the block instantly, but stores

    # it in the `blocks` array to be executed later.

    #

    # @yieldpublic [Gamefic::Plot]

    def script &block
      blocks.push block
    end
  end

  def self.included klass
    klass.extend ClassMethods
  end

  private

  # Execute all the scripts that were added by the `script` class method.

  #

  def run_scripts
    self.class.blocks.each { |blk| stage &blk }
  end
end

#theaterObject

The object that acts as an isolated namespace for staged code.



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
# File 'lib/gamefic/scriptable.rb', line 33

module Scriptable
  module ClassMethods
    # An array of blocks that were added by the `script` class method.

    #

    # @return [Array<Proc>]

    def blocks
      @blocks ||= []
    end

    # Add a block to be executed by the instance's `stage` method.

    #

    # Note that `script` does not execute the block instantly, but stores

    # it in the `blocks` array to be executed later.

    #

    # @yieldpublic [Gamefic::Plot]

    def script &block
      blocks.push block
    end
  end

  def self.included klass
    klass.extend ClassMethods
  end

  private

  # Execute all the scripts that were added by the `script` class method.

  #

  def run_scripts
    self.class.blocks.each { |blk| stage &blk }
  end
end