Last active
October 25, 2017 14:23
-
-
Save sanjayginde/a676d86a47377169057cfb5b8d38d294 to your computer and use it in GitHub Desktop.
PJAX concern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
%title=h ((title=yield(:title)).blank?) ? "Contently" : "#{title} : Contently".html_safe | |
=yield | |
=yield :javascript |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# More info: https://github.com/defunkt/jquery-pjax | |
module Concerns::Pjaxable | |
extend ActiveSupport::Concern | |
included do | |
layout proc { |c| pjax_request? ? pjax_layout : application_layout } | |
helper_method :pjax_request? | |
rescue_from Pjax::Unsupported, :with => :pjax_unsupported | |
before_filter :strip_pjax_param, :if => :pjax_request? | |
before_filter :set_pjax_url, :if => :pjax_request? | |
end | |
class Error < StandardError; end | |
class Unsupported < Error; end | |
module ClassMethods | |
def uses_application_layout(the_layout) | |
define_method 'application_layout' do | |
return send(the_layout) if the_layout.is_a? Symbol | |
the_layout.to_s | |
end | |
end | |
end | |
protected | |
def pjax_request? | |
env['HTTP_X_PJAX'].present? | |
end | |
def pjax_layout | |
'pjax' | |
end | |
def application_layout | |
'application' | |
end | |
def pjax_container | |
return unless pjax_request? | |
request.headers['X-PJAX-Container'] | |
end | |
def pjax_unsupported | |
head :not_acceptable | |
end | |
# Call in a before_filter or in an action to disable pjax on an action. | |
# | |
# Examples | |
# | |
# before_filter :prevent_pjax! | |
# | |
# def login | |
# prevent_pjax! | |
# # ... | |
# end | |
# | |
def prevent_pjax! | |
raise Pjax::Unsupported if pjax_request? | |
end | |
def strip_pjax_param | |
params.delete(:_pjax) | |
request.env['QUERY_STRING'] = request.env['QUERY_STRING'].sub(/_pjax=[^&]+&?/, '') | |
request.env.delete('rack.request.query_string') | |
request.env.delete('rack.request.query_hash') | |
request.env.delete('action_dispatch.request.query_parameters') | |
request.instance_variable_set('@original_fullpath', nil) | |
request.instance_variable_set('@fullpath', nil) | |
end | |
def set_pjax_url | |
response.headers['X-PJAX-URL'] = request.url | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment