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



52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/rails-ajax/controller.rb', line 52

def redirect_to(options = {}, response_status = {})
  if (RailsAjax.config.enabled? and 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
# File 'lib/rails-ajax/controller.rb', line 8

def render(*options, &block)
  if (RailsAjax.config.enabled?)
    args = _normalize_args(*options, &block)
    if ((request.xhr?) and
        (!args.has_key?(:partial)) and
        (!args.has_key?(:layout)) and
        (!args.has_key?(:json)) and
        (params['format'] != 'json') and
        (self.content_type != 'application/json'))
      logger.debug "[RailsAjax] render: options=#{options.inspect} block?#{block != nil} 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
      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