Sha256: 498be5492ef6c3a09915bad3041177f74feb84e36e5f1f9085e29af8669a5712

Contents?: true

Size: 1015 Bytes

Versions: 6

Compression:

Stored size: 1015 Bytes

Contents

require 'rack'

module Rack
  module Rewritten
    class Canonical
      def initialize(app)
        @app = app
      end

      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, %(<link rel="canonical" href="#{target}"/>))
            headers['Content-Length'] = body.length.to_s
            response = [body]
          end

        end
        [status, headers, response]
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
rewritten-0.16.5 lib/rack/canonical.rb
rewritten-0.16.4 lib/rack/canonical.rb
rewritten-0.16.3 lib/rack/canonical.rb
rewritten-0.16.2 lib/rack/canonical.rb
rewritten-0.16.1 lib/rack/canonical.rb
rewritten-0.16.0 lib/rack/canonical.rb