Rjax
Solve template dispatch on ajax request
<img src=“https://codeclimate.com/github/jalkoby/rjax.png” /> <img src=“https://travis-ci.org/jalkoby/rjax.png?branch=master” alt=“Build Status” /> <img src=“https://badge.fury.io/rb/rjax.png” alt=“Gem Version” />
Installation
Add this line to your application’s Gemfile:
gem 'rjax'
And then execute:
$ bundle
Or install it yourself as:
$ gem install rjax
Usage
Rjax will be useful if you have a lot actions which serve http and ajax requests. It might looks like:
def index
@users = User.all
render :partials => 'users', :locals => { :users => @users } if request.xhr?
# or
render :index_ajax if request.xhr?
end
Rjax adds ‘rjax` methods in rails controllers.
class UsersController < ApplicationController
def index
@users = User.all
rjax
end
# calling rjax method without arguments will render template;
# the name of template will contain action_name and wrapper;
# in this case expected `index_rjax` template;
def index
@users = User.all
rjax @users
end
# calling rjax method is similar to view helper render %collection%;
# the only different is also looks for partial with wrapped name;
# in this case it will look for partial `_user_rjax` or `_user` and pass variable `user`;
def index
@users = User.all
rjax :users => @users, :other => :variable
end
# calling rjax method with Hash will render partial with locals specified in hash;
# the name of partial might be specified in :partial key;
# if :partial key is missed expected that view folder contains partial with plural form of controller with or without wrapper;
# in this case it will be `_users_rjax` or `_users` partial
def show
@user = User.find(params[:id])
rjax @user
end
# in other cases rjax will render partial and pass this variable into partial;
# the name of partial will be singular form of controller with or without wrapper;
# in this case it will be `_user_rjax` or `_user` partial
# it also support respond_with
def index
respond_with do |format|
format.html { rjax }
format.json { rjax }
format.xml { rjax }
end
end
end
If you don’t like rjax default wrapper you can configure it:
# config/initializers/rjax.rb
Rjax.config do |config|
config.suffix = "suffix"
config.prefix = "prefix"
end
prefix_%template%_suffix
_prefix_%partial%_suffix
Contributing
-
Fork it
-
Create your feature branch (‘git checkout -b my-new-feature`)
-
Commit your changes (‘git commit -am ’Add some feature’‘)
-
Push to the branch (‘git push origin my-new-feature`)
-
Create new Pull Request