Class: Rack::Rewritten::Canonical

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/canonical.rb

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Canonical

Returns a new instance of Canonical.



9
10
11
# File 'lib/rack/canonical.rb', line 9

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/rack/canonical.rb', line 13

def call(env)
  req = Rack::Request.new(env)

  status, headers, response = @app.call(req.env)

  if status == 200 && headers["Content-Type"] =~ /text\/html|application\/xhtml\+xml/
    body = ""
    response.each { |part| body << part }
    index = body.rindex("</head>")
    if index
      # go with a request duplicate since infinitive works on translations
      target_req = req.dup
      target_req.path_info = ::Rewritten.infinitive( ::Rewritten.get_current_translation(req.path) )
      target_req.env['QUERY_STRING'] = ''
      target = target_req.url

      body.insert(index, %Q|<link rel="canonical" href="#{target}"/>| )
      headers["Content-Length"] = body.length.to_s
      response = [body]
    end

  end
  [status, headers, response]
end