Renders partials to your views asynchronously. This is done through adding Javascript code that does AJAX request to your controller which then renders your partial.
Workflow:
- user visits a page =>
- AJAX request on the controller action =>
- controller renders a partial =>
- partials renders in the place where you put
render_async
helper
Javascript is injected into <%= content_for :render_async %>
so you choose
where to put it.
Add this line to your application's Gemfile:
gem 'render_async'
And then execute:
$ bundle install
-
Include
render_async
view helper somewhere in your views:# app/views/comments/show.html.erb <%= render_async comment_stats_path %>
-
Then create a route that will
config/routes.rb
# config/routes.rb get :comment_stats, controller: :comments
-
Fill in the logic in your controller
# app/controllers/comments_controller.rb def comment_stats @stats = Comment.get_stats render partial: "comment_stats" end
-
Create a partial that will render
# app/views/comments/_comment_stats.html.erb <div class="col-md-6"> <%= @stats %> </div>
-
Add
content_for
in your base view file# application.html.erb <%= content_for :render_async %>
-
Add styles in your application.css
/* application.css */ /* *= require render_async */
-
(optional) Pass
event_name: <event name>
to hook events# application.html.erb <%= content_for :render_async, event_name: 'foo' %>
// application.js document.addEventListener('success-foo', function () { console.log('success') }); document.addEventListener('error-foo', function () { console.log('fail') }); // Call `complete-<event_name>` whether success or error document.addEventListener('complete-foo', function () { console.log('complete') });
render_async
takes two arguments, path
and html_options
.
path
is the ajax-capable controller action you're looking to call viaget
. e.g.comments_stats_path
,posts_path
, etc.html_options
is an optional hash that gets passed to a railsjavascript_tag
, to drop html tags into thescript
element.
Example utilizing html_options
with a nonce
:
<%= render_async users_path, nonce: 'lWaaV6eYicpt+oyOfcShYINsz0b70iR+Q1mohZqNaag=' %>
After checking out the repo, run bin/setup
to install dependencies. Then, run
rake spec
to run the tests. You can also run bin/console
for an interactive
prompt that will allow you to experiment.
To install this gem onto your local machine, run bundle exec rake install
. To
release a new version, update the version number in version.rb
, and then run
bundle exec rake release
, which will create a git tag for the version, push
git commits and tags, and push the .gem
file to
rubygems.org.
Bug reports and pull requests are welcome on GitHub at https://github.com/renderedtext/render_async.
The gem is available as open source under the terms of the MIT License.