Class: Rack::Pjax

Inherits:
Object
  • Object
show all
Includes:
Utils
Defined in:
lib/rack/pjax.rb,
lib/rack/pjax/version.rb

Constant Summary collapse

VERSION =
"1.0.0"

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Pjax

Returns a new instance of Pjax



7
8
9
# File 'lib/rack/pjax.rb', line 7

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# 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.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'] &&= bytesize(new_body).to_s
  headers['X-PJAX-URL'] ||= Rack::Request.new(env).fullpath

  [status, headers, [new_body]]
end