Class: Utopia::Middleware::Controller

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

Defined Under Namespace

Classes: Base, Variables

Constant Summary collapse

CONTROLLER_RB =
"controller.rb"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ Controller

Returns a new instance of Controller.



141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/utopia/middleware/controller.rb', line 141

def initialize(app, options = {})
	@app = app
	@root = options[:root] || Utopia::Middleware::default_root

	LOG.info "** #{self.class.name}: Running in #{@root}"

	@controllers = {}
	@cache_controllers = (UTOPIA_ENV == :production)

	if options[:controller_file]
		@controller_file = options[:controller_file]
	else
		@controller_file = "controller.rb"
	end
end

Instance Attribute Details

#appObject (readonly)

Returns the value of attribute app.



157
158
159
# File 'lib/utopia/middleware/controller.rb', line 157

def app
  @app
end

Instance Method Details

#call(env) ⇒ Object



203
204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'lib/utopia/middleware/controller.rb', line 203

def call(env)
	env["utopia.controller"] ||= Variables.new
	
	request = Rack::Request.new(env)

	path = Path.create(request.path_info)
	fetch_controllers(path).each do |controller|
		if result = controller.process!(path, request)
			return result
		end
	end

	return @app.call(env)
end

#fetch_controllers(path) ⇒ Object



194
195
196
197
198
199
200
201
# File 'lib/utopia/middleware/controller.rb', line 194

def fetch_controllers(path)
	controllers = []
	path.ascend do |parent_path|
		controllers << lookup(parent_path)
	end

	return controllers.compact.reverse
end

#load_file(path) ⇒ Object



169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# File 'lib/utopia/middleware/controller.rb', line 169

def load_file(path)
	if path.directory?
		base_path = File.join(@root, path.components)
	else
		base_path = File.join(@root, path.dirname.components)
	end

	controller_path = File.join(base_path, CONTROLLER_RB)

	if File.exist?(controller_path)
		klass = Class.new(Base)
		klass.const_set('BASE_PATH', base_path)
		
		$LOAD_PATH.unshift(base_path)
		
		klass.class_eval(File.read(controller_path), controller_path)
		
		$LOAD_PATH.delete(base_path)
		
		return klass.new(self)
	else
		return nil
	end
end

#lookup(path) ⇒ Object



159
160
161
162
163
164
165
166
167
# File 'lib/utopia/middleware/controller.rb', line 159

def lookup(path)
	if @cache_controllers
		return @controllers.fetch(path.to_s) do |key|
			@controllers[key] = load_file(path)
		end
	else
		return load_file(path)
	end
end