Class: Utopia::Middleware::Redirector

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

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Redirector.



114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/utopia/middleware/redirector.rb', line 114

def initialize(app, options = {})
	@app = app

	@strings = options[:strings] || {}
	@patterns = options[:patterns] || {}

	@strings = normalize_strings(@strings)
	@patterns = normalize_patterns(@patterns)

	@errors = options[:errors]

	LOG.info "** #{self.class.name}: Running with #{@strings.size + @patterns.size} rules"
end

Instance Method Details

#call(env) ⇒ Object



136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
# File 'lib/utopia/middleware/redirector.rb', line 136

def call(env)
	base_path = env['PATH_INFO']

	if uri = @strings[base_path]
		return redirect(@strings[base_path], base_path)
	end

	@patterns.each do |pattern, uri|
		if match_data = pattern.match(base_path)
			result = redirect(uri, match_data)

			return result if result != nil
		end
	end

	response = @app.call(env)

	if @errors && response[0] >= 400 && uri = @errors[response[0]]
		error_request = env.merge("PATH_INFO" => uri, "REQUEST_METHOD" => "GET")
		error_response = @app.call(error_request)

		if error_response[0] >= 400
			raise FailedRequestError.new(env['PATH_INFO'], response[0], uri, error_response[0])
		else
			# Feed the error code back with the error document
			error_response[0] = response[0]
			return error_response
		end
	else
		return response
	end
end

#redirect(uri, match_data) ⇒ Object



128
129
130
131
132
133
134
# File 'lib/utopia/middleware/redirector.rb', line 128

def redirect(uri, match_data)
	if uri.respond_to? :call
		return uri.call(match_data)
	else
		return [301, {"Location" => uri.to_s}, []]
	end
end