jngo (owner)

Fork Of

gist: 130373 by freelan... Returning HTML in AJAX call...

Revisions

gist: 130420 Download_button fork
public
Description:
Returning HTML in AJAX calls for Ruby on Rails.
Public Clone URL: git://gist.github.com/130420.git
Embed All Files: show embed
application_controller.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# Three things to add:
# * before_filter call
# * action_has_layout? method (if you have one, combine them)
# * adjust_for_inline
#
class ApplicationController < ActionController::Base
  # ...
  
  before_filter :adjust_for_inline
  
  # ...
  
  private
  
  # We don't want no stinking layout if it's an AJAX request.
  def action_has_layout?
    request.format != :inline && super
  end
  
  def adjust_for_inline
    request.format = :inline if request.xhr?
  end
 
  # ...
end
config/initializers/mime_types.rb #
1
2
3
# Add this line to your existing file.
# Jury's out on the best name for the pseudo-mimetype though.
Mime::Type.register_alias "text/html", :inline
my_controller.rb #
1
2
3
4
5
6
7
8
9
10
# A long time ago, in an action far far away
def index
  # ...
  respond_to do |wants|
    wants.inline {
      # ideally use your own view (index.inline.erb)
      render :text => 'success!'
    }
  end
end