Module: Ballast::Concerns::AjaxHandling
- Extended by:
- ActiveSupport::Concern
- Defined in:
- lib/ballast/concerns/ajax_handling.rb
Overview
A concern to handle AJAX and HTTP requests.
Instance Method Summary collapse
-
#ajax_request? ⇒ Boolean
Checks if the current request is AJAX.
-
#allow_cors(allow_origin: "*", allow_methods: [:post, :get, :options], allow_headers: "*", max_age: 1.year, allow_credentials: false) ⇒ Object
Allows HTTP Cross-Origin Resource Sharing.
-
#generate_robots_txt(configuration = nil) ⇒ Object
(also: #disallow_robots)
Generates a `robots.txt file.
-
#prepare_ajax_response(status: :ok, data: {}, error: nil) ⇒ Object
Prepares an AJAX response.
-
#prevent_caching ⇒ Object
Prevents HTTP caching.
Instance Method Details
#ajax_request? ⇒ Boolean
Checks if the current request is AJAX.
16 17 18 |
# File 'lib/ballast/concerns/ajax_handling.rb', line 16 def ajax_request? request.safe_send(:xhr?).to_boolean || params[:xhr].to_boolean end |
#allow_cors(allow_origin: "*", allow_methods: [:post, :get, :options], allow_headers: "*", max_age: 1.year, allow_credentials: false) ⇒ Object
Allows HTTP Cross-Origin Resource Sharing.
45 46 47 48 49 50 51 52 53 54 |
# File 'lib/ballast/concerns/ajax_handling.rb', line 45 def allow_cors(allow_origin: "*", allow_methods: [:post, :get, :options], allow_headers: "*", max_age: 1.year, allow_credentials: false) headers.merge!({ "Access-Control-Allow-Origin" => allow_origin, "Access-Control-Allow-Methods" => allow_methods.map { |m| m.to_s.upcase }.join(", "), "Access-Control-Allow-Headers" => allow_headers, "Access-Control-Max-Age" => max_age.to_i.to_s }) headers["Access-Control-Allow-Credentials"] = "true" if allow_credentials end |
#generate_robots_txt(configuration = nil) ⇒ Object Also known as: disallow_robots
Generates a `robots.txt file.
59 60 61 62 63 64 65 66 67 68 69 |
# File 'lib/ballast/concerns/ajax_handling.rb', line 59 def generate_robots_txt(configuration = nil) configuration ||= {"*" => "/"} rv = configuration.reduce([]) do |accu, (agent, paths)| paths = paths.ensure_array.map { |e| "Disallow: #{e}" } accu << "User-agent: #{agent}\n#{paths.join("\n")}" accu end render(text: rv.join("\n\n"), content_type: "text/plain") end |
#prepare_ajax_response(status: :ok, data: {}, error: nil) ⇒ Object
Prepares an AJAX response.
25 26 27 |
# File 'lib/ballast/concerns/ajax_handling.rb', line 25 def prepare_ajax_response(status: :ok, data: {}, error: nil) Ballast::AjaxResponse.new(status: status, data: data, error: error, transport: self) end |
#prevent_caching ⇒ Object
Prevents HTTP caching.
30 31 32 33 34 35 36 |
# File 'lib/ballast/concerns/ajax_handling.rb', line 30 def prevent_caching response.headers.merge!({ "Cache-Control" => "no-cache, no-store, max-age=0, must-revalidate", "Pragma" => "no-cache", "Expires" => "Fri, 01 Jan 1990 00:00:00 GMT" }) end |