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.



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

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

	@strings = {}
	@patterns = {}

	normalize_keys(options[:redirects]) if options[:redirects]

	@errors = options[:errors]

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

Instance Method Details

#call(env) ⇒ Object



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 138

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 = base_path.match(pattern)
			return redirect(uri, match_data)
		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



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

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