Class: Utopia::Middleware::Redirector

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

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



83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/utopia/middleware/redirector.rb', line 83

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

  @strings = options[:strings] || {}
  @patterns = options[: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 = options[:errors]
end

Class Method Details

.moved(source_root, destination_root) ⇒ Object

Redirects a whole source tree to a destination tree, given by the roots.



44
45
46
47
48
49
50
51
# File 'lib/utopia/middleware/redirector.rb', line 44

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



111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'lib/utopia/middleware/redirector.rb', line 111

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



103
104
105
106
107
108
109
# File 'lib/utopia/middleware/redirector.rb', line 103

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