class Evaluator
An evaluator is lazy read-only view of an environment. It memoizes all method calls.
Definitions
def self.wrap(environment)
Create an evaluator wrapper for an environment.
Signature
-
parameter
environment
Environment
The environment to wrap.
-
returns
Evaluator
A new evaluator instance.
Implementation
def self.wrap(environment)
evaluator = ::Class.new(self)
facet = ::Module.new
environment.included(facet)
evaluator.include(facet)
keys = []
# Memoize all instance methods:
facet.instance_methods.each do |name|
instance_method = facet.instance_method(name)
# Only memoize methods with no arguments:
if instance_method.arity == 0
keys << name
evaluator.define_method(name) do
@cache[name] ||= super()
end
end
end
# This lists all zero-argument methods:
evaluator.define_method(:keys) {keys}
return evaluator.new
end
def initialize
Initialize a new evaluator.
Implementation
def initialize
@cache = {}
end
def inspect
Inspect representation of the evaluator.
Signature
-
returns
String
A string representation of the evaluator with its keys.
Implementation
def inspect
"#<#{Evaluator} #{self.keys}>"
end
def to_h
Convert the evaluator to a hash.
Signature
-
returns
Hash
A hash with all evaluated keys and values.
Implementation
def to_h
# Ensure all keys are evaluated:
self.keys.each do |name|
self.__send__(name)
end
return @cache
end
def to_json(...)
Convert the evaluator to JSON.
Signature
-
parameter
arguments
Array
Arguments passed to to_json.
-
returns
String
A JSON representation of the evaluator.
Implementation
def to_json(...)
self.to_h.to_json(...)
end
def [](key)
Get value for a given key.
Signature
-
parameter
key
Symbol
The key to look up.
-
returns
Object, nil
The value for the key, or nil if not found.
Implementation
def [](key)
if self.key?(key)
self.__send__(key)
end
end
def key?(key)
Check if a key is available.
Signature
-
parameter
key
Symbol
The key to check.
-
returns
Boolean
True if the key exists.
Implementation
def key?(key)
self.keys.include?(key)
end