Module: RailsAjax::Controller

Included in:
ActionController::Base
Defined in:
lib/rails-ajax/controller.rb

Overview

Module defining new methods that will be part of every controller

Instance Method Summary collapse

Instance Method Details

#redirect_to(options = {}, response_status = {}) ⇒ Object

Render a redirection Adapt to AJAX calls


58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/rails-ajax/controller.rb', line 58

def redirect_to(options = {}, response_status = {})
  if RailsAjax.config.enabled? && request.xhr?
    logger.debug "[RailsAjax] redirect_to: options=#{options.inspect} response_status=#{response_status.inspect}"
    # Use 'application/json'
    self.content_type = 'application/json'
    self.response_body = get_json_response(
      redirect_to: url_for(options)
    ).to_json
  else
    super(options, response_status)
  end
end

#render(*options, &block) ⇒ Object

Render Adapt to AJAX calls, by returning the following JSON object that will be interpreted by client side JavaScript.


8
9
10
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
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/rails-ajax/controller.rb', line 8

def render(*options, &block)
  if RailsAjax.config.enabled?
    args = _normalize_args(*options, &block)
    if request.xhr? &&
       !args.key?(:partial) &&
       !args.key?(:layout) &&
       !args.key?(:json) &&
       params['format'] != 'json' &&
       content_type != 'application/json'
      logger.debug "[RailsAjax] render: options=#{options.inspect} block?#{block} flash=#{flash.inspect} | Normalized arguments: #{args.inspect}"

      # If we have a redirection, use redirect_to
      if args[:location].nil?
        # Complete arguments if needed
        # We don't want a special layout for Ajax requests: this was asked using AJAX for a page to be displayed in the main content
        args[:layout] = false
        # Render
        main_content = render_to_string(args, &block)

        # Send JSON result
        # Use 'application/json'
        self.content_type = 'application/json'
        self.response_body = get_json_response(
          elements_to_refresh: {
            RailsAjax.config.main_container => main_content
          }
        ).to_json

        # Disable the cache as what is returned is not the complete page: browsers should not cache it.
        response.headers['Cache-Control'] = 'no-cache, no-store, max-age=0, must-revalidate'
        response.headers['Pragma'] = 'no-cache'
        response.headers['Expires'] = 'Fri, 01 Jan 1990 00:00:00 GMT'

      elsif args[:status].nil?
        redirect_to args[:location]
      else
        redirect_to args[:location], args[:status]
      end

    else
      super(*options, &block)
    end
  else
    super(*options, &block)
  end

end