Sha256: 0518da725f2d37079419b3d8df5815d3fd08d67720819d4fe2ccae3c8b706315

Contents?: true

Size: 1.37 KB

Versions: 1

Compression:

Stored size: 1.37 KB

Contents

module Gamefic
  module Scriptable
    # Functions that provide proxies for referencing a narrative's entities
    # from class-level scripts.
    #
    module Proxy
      # The object that fetches a proxied entity.
      #
      class Agent
        attr_reader :symbol

        # @param symbol [Symbol, Integer]
        def initialize symbol
          @symbol = symbol
        end

        def fetch container
          if symbol.to_s =~ /^\d+$/
            Stage.run(container, symbol) { |sym| entities[sym] }
          elsif symbol.to_s.start_with?('@')
            Stage.run(container, symbol) { |sym| instance_variable_get(sym) }
          else
            Stage.run(container, symbol) { |sym| send(sym) }
          end
        end
      end

      # Proxy a method or instance variable.
      #
      # @example
      #   proxy(:method_name)
      #   proxy(:@instance_variable_name)
      #
      # @param symbol [Symbol]
      def proxy symbol
        Agent.new(symbol)
      end

      # @param object [Object]
      # @return [Object]
      def unproxy object
        case object
        when Agent
          object.fetch self
        when Array
          object.map { |obj| unproxy obj }
        when Hash
          object.transform_values { |val| unproxy val }
        else
          object
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
gamefic-3.0.0 lib/gamefic/scriptable/proxy.rb