Class: Utopia::Controller::Variables

Inherits:
Object
  • Object
show all
Defined in:
lib/utopia/controller/variables.rb

Overview

Provides a stack-based instance variable lookup mechanism. It can flatten a stack of controllers into a single hash.

Instance Method Summary collapse

Constructor Details

#initializeVariables

Initialize an empty controller stack.



11
12
13
# File 'lib/utopia/controller/variables.rb', line 11

def initialize
	@controllers = []
end

Instance Method Details

#<<(controller) ⇒ Object

Push a controller after copying variables from the previous controller.



24
25
26
27
28
29
30
31
32
33
# File 'lib/utopia/controller/variables.rb', line 24

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

#[](key) ⇒ Object

Fetch a variable from the innermost controller.



71
72
73
# File 'lib/utopia/controller/variables.rb', line 71

def [] key
	fetch("@#{key}".to_sym, nil)
end

#fetch(key, default = self) ⇒ Object

We use self as a seninel



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/utopia/controller/variables.rb', line 36

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

#to_hashObject

Convert the current controller's instance variables to attributes.



54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/utopia/controller/variables.rb', line 54

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

#topObject

Return the innermost controller.



17
18
19
# File 'lib/utopia/controller/variables.rb', line 17

def top
	@controllers.last
end