class Variables
Provides a stack-based instance variable lookup mechanism. It can flatten a stack of controllers into a single hash.
Definitions
def initialize
Initialize an empty controller stack.
Implementation
def initialize
@controllers = []
end
def top
Return the innermost controller.
Signature
-
returns
Controller::Base | Nil The current controller.
Implementation
def top
@controllers.last
end
def <<(controller)
Push a controller after copying variables from the previous controller.
Signature
-
parameter
controllerUtopia::Controller::Base The controller instance.
-
returns
self This variables stack.
Implementation
def << controller
if top = self.top
# This ensures that most variables will be at the top and controllers can naturally interactive with instance variables:
controller.copy_instance_variables(top)
end
@controllers << controller
return self
end
def fetch(key, default=self)
We use self as a seninel
Implementation
def fetch(key, default=self)
if controller = self.top
if controller.instance_variables.include?(key)
return controller.instance_variable_get(key)
end
end
if block_given?
yield(key)
elsif !default.equal?(self)
return default
else
raise KeyError.new(key)
end
end
def to_hash
Convert the current controller's instance variables to attributes.
Signature
-
returns
Hash(Symbol, Object) The current controller attributes.
Implementation
def to_hash
attributes = {}
if controller = self.top
controller.instance_variables.each do |name|
key = name[1..-1].to_sym
attributes[key] = controller.instance_variable_get(name)
end
end
return attributes
end
def [](key)
Fetch a variable from the innermost controller.
Signature
-
parameter
keyString | Symbol The lookup key.
-
returns
Object | Nil The variable value, or
nilwhen it is undefined.
Implementation
def [] key
fetch("@#{key}".to_sym, nil)
end