Sha256: 3ca54e89eacf5784fa9c757dc00bebcd3b48de3714ad8e3c28679fc25cd6a97d

Contents?: true

Size: 1 KB

Versions: 5

Compression:

Stored size: 1 KB

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, %Q|<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

5 entries across 5 versions & 1 rubygems

Version Path
rewritten-0.15.2 lib/rack/canonical.rb
rewritten-0.15.1 lib/rack/canonical.rb
rewritten-0.15.0 lib/rack/canonical.rb
rewritten-0.14.2 lib/rack/canonical.rb
rewritten-0.14.1 lib/rack/canonical.rb