class Rack::Pjax

Constants

VERSION

Public Class Methods

new(app) click to toggle source
# File lib/rack/pjax.rb, line 7
def initialize(app)
  @app = app
end

Public Instance Methods

call(env) click to toggle source
# File lib/rack/pjax.rb, line 11
def call(env)
  status, headers, body = @app.call(env)
  return [status, headers, body] unless pjax?(env)

  headers = HeaderHash.new(headers)

  new_body = ""
  body.each do |b|
    b = b.dup.force_encoding('UTF-8') if RUBY_VERSION > '1.9.0'

    parsed_body = Nokogiri::HTML(b)
    container = parsed_body.at(container_selector(env))

    new_body << begin
      if container
        title = parsed_body.at("title")

        "%s%s" % [title, container.inner_html]
      else
        b
      end
    end
  end

  body.close if body.respond_to?(:close)

  headers['Content-Length'] &&= new_body.bytesize.to_s
  headers['X-PJAX-URL'] ||= Rack::Request.new(env).fullpath

  [status, headers, [new_body]]
end

Protected Instance Methods

container_selector(env) click to toggle source
# File lib/rack/pjax.rb, line 48
def container_selector(env)
  env['HTTP_X_PJAX_CONTAINER'] || "[@data-pjax-container]"
end
pjax?(env) click to toggle source
# File lib/rack/pjax.rb, line 44
def pjax?(env)
  env['HTTP_X_PJAX']
end