Class: Utopia::Middleware::Redirector
- Inherits:
-
Object
- Object
- Utopia::Middleware::Redirector
- Defined in:
- lib/utopia/middleware/redirector.rb
Class Method Summary collapse
-
.moved(source_root, destination_root) ⇒ Object
Redirects a whole source tree to a destination tree, given by the roots.
Instance Method Summary collapse
- #call(env) ⇒ Object
-
#initialize(app, options = {}) ⇒ Redirector
constructor
A new instance of Redirector.
- #redirect(uri, match_data) ⇒ Object
Constructor Details
#initialize(app, options = {}) ⇒ Redirector
Returns a new instance of Redirector.
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 |
# File 'lib/utopia/middleware/redirector.rb', line 124 def initialize(app, = {}) @app = app @strings = [:strings] || {} @patterns = [:patterns] || [] @patterns.collect! do |rule| if Symbol === rule[0] self.class.send(*rule) else rule end end @strings = normalize_strings(@strings) @patterns = normalize_patterns(@patterns) @errors = [:errors] LOG.info "** #{self.class.name}: Running with #{@strings.size + @patterns.size} rules" end |
Class Method Details
.moved(source_root, destination_root) ⇒ Object
Redirects a whole source tree to a destination tree, given by the roots.
85 86 87 88 89 90 91 92 |
# File 'lib/utopia/middleware/redirector.rb', line 85 def self.moved(source_root, destination_root) return [ /^#{Regexp.escape(source_root)}(.*)$/, lambda do |match| [301, {"Location" => (destination_root + match[1]).to_s}, []] end ] end |
Instance Method Details
#call(env) ⇒ Object
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 |
# File 'lib/utopia/middleware/redirector.rb', line 154 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
146 147 148 149 150 151 152 |
# File 'lib/utopia/middleware/redirector.rb', line 146 def redirect(uri, match_data) if uri.respond_to? :call return uri.call(match_data) else return [301, {"Location" => uri.to_s}, []] end end |