Class: Utopia::Redirector
- Inherits:
-
Object
- Object
- Utopia::Redirector
- Defined in:
- lib/utopia/redirector.rb
Constant Summary collapse
- DIRECTORY_INDEX =
This redirects directories to the directory + ‘index’
[/^(.*)\/$/, lambda{|prefix| [307, {HTTP::LOCATION => "#{prefix}index"}, []]}].freeze
Class Method Summary collapse
-
.moved(source_root, destination_root) ⇒ Object
Redirects a whole source tree to a destination tree, given by the roots.
- .starts_with(source_root, destination_uri) ⇒ Object
Instance Method Summary collapse
- #call(env) ⇒ Object
- #freeze ⇒ 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.
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 |
# File 'lib/utopia/redirector.rb', line 91 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] self.freeze end |
Class Method Details
.moved(source_root, destination_root) ⇒ Object
Redirects a whole source tree to a destination tree, given by the roots.
43 44 45 46 47 48 49 50 |
# File 'lib/utopia/redirector.rb', line 43 def self.moved(source_root, destination_root) return [ /^#{Regexp.escape(source_root)}(.*)$/, lambda do |match| [301, {HTTP::LOCATION => (destination_root + match[1]).to_s}, []] end ] end |
.starts_with(source_root, destination_uri) ⇒ Object
52 53 54 55 56 57 |
# File 'lib/utopia/redirector.rb', line 52 def self.starts_with(source_root, destination_uri) return [ /^#{Regexp.escape(source_root)}/, destination_uri ] end |
Instance Method Details
#call(env) ⇒ Object
129 130 131 132 133 134 135 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 |
# File 'lib/utopia/redirector.rb', line 129 def call(env) base_path = env[Rack::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(Rack::PATH_INFO => uri, Rack::REQUEST_METHOD => Rack::GET) error_response = @app.call(error_request) if error_response[0] >= 400 raise FailedRequestError.new(env[Rack::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 |
#freeze ⇒ Object
113 114 115 116 117 118 119 |
# File 'lib/utopia/redirector.rb', line 113 def freeze @strings.freeze @patterns.freeze @errors.freeze super end |