• Stars
    star
    166
  • Rank 227,748 (Top 5 %)
  • Language
    Ruby
  • Created almost 11 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Enhanced AJAX handling for Rails apps

Turboboost

Turboboost extends the power of Turbolinks into the forms of your Rails app and provides additional convenient AJAX handlers for forms and links. It aims to be a seemless and logical addition to any Turbolinks-rocking Rails 3.2+ app. Currently it depends on jQuery. The main features are:

  • Form response redirection is handled by Turbolinks.
  • Customizable success and error handling through registered JavaScript, with support for Rails' Flash and optional error rendering built-in.
  • Responses can also be rendered within a scoped DOM target using jQuery selectors.
Disclaimer

In recent history Turbolinks has started to emulate some of these features with a slightly different approach. I will continue to support this library if people are still finding it useful.

Installation

In your Gemfile
gem 'turboboost'

Or to live on the very edge:

gem 'turboboost', github: 'waymondo/turboboost'

Then bundle install.

In your application.js
//= require turboboost

This will also require jQuery, jquery-ujs, Turbolinks, if not already required. If you wish to register your scripts manually, you can like so:

//= require path/to/vendored/jquery
//= require jquery_ujs
//= require turbolinks
//= require turboboost/turboboost
In your view files

Add turboboost: true to your form / link helpers:

<%= form_for :resource, turboboost: true do |f| ... %>

<%= link_to "Turboboosted Link", resource_path, turboboost: true %>

Or you can add the data attribute manually:

<form data-remote data-turboboost action="/foo"></form>

<a data-remote data-turboboost href="/bar"></a>

Redirection with Turbolinks

In its simplest server-side implementation, a basic Turboboost controller action with redirection might look like this:

def create
  post = Post.create!(params[:post]) # <- trigger exception if model is invalid
  redirect_to post, notice: 'Post was successfully created.'
end

If the post is successfully created through a Turboboost-ed form, the app will visit the post's URL with Turbolinks. Otherwise, the redirect will happen like normal. You can opt out of redirecting through Turboboost with the attribute flag data-no-turboboost-redirect.

Form GET requests

If a Turboboost form makes a GET request, it will serialize the form's data and then visit its action URL with the data serialized as parameters with Turbolinks. This allows Turbolinks-powered cached push/popState history navigation of controller actions with different parameter values (like a search form).

Automatic form disabling handling

To prevent double-clicks on submit buttons from firing the form's action twice, Turboboost comes with automatic form disabling/enabling by default. When you restore a page from Turbolinks' cache, it will re-enable any submit buttons that it had disabled. You can disable this behavior and control your form's submittable state manually with:

Turboboost.handleFormDisabling = false

Error handling

If the post in our example above is invalid, no redirect will happen and a rescue_from handler will pass the errors to JavaScript through the turboboost:error event:

$(document).on "turboboost:error", (e, errors) ->
  console.log(errors) # <- JSON array of errors messages

You can also trigger the JSON error messages explicitly with the method render_turboboost_errors_for(record) if you don't want to use the default rescue_from handler:

def create
  @post = Post.new(post_params)
  if @post.save
    flash[:notice] = 'Post was successfully created.'
    redirect_to @post
  else
    respond_to do |format|
      format.html { render :new }
      format.js { render_turboboost_errors_for(@post) }
    end
  end
end

To note: If you are rendering a response from a Turboboost-ed form or link, you will need to specify its rendering scope.

Check out the test controllers for more examples of controller syntax.

Automatic error message insertion

Optionally, Turboboost can render returned errors with the same HTML structure used in the default Rails generators and prepend it to the form. The HTML structure looks like this:

<div id="error_explanation">
  <ul>
    {{#errors}}
      <li>{{this}}</li>
    {{/errors}}
  </ul>
</div>

To turn it on:

Turboboost.insertErrors = true # same as 'prepend'
# other possible values:
# Turboboost.insertErrors = 'append'
# Turboboost.insertErrors = 'beforeSubmit'
# Turboboost.insertErrors = 'afterSubmit'
# can also be a jQuery selector:
# Turboboost.insertErrors = '.error-wrap'

Error internationalization

Turboboost will handle invalid ActiveRecord and ActiveModel error messages as well as basic HTTP error messages. For ActiveRecord validations, it will use Rails' I18n lookup to retrieve the message wording. For other raised exceptions, you can customize the basic wording using the I18n namespace format turboboost.errors.#{error.class.name}:

en:
  turboboost:
    errors:
      "ActiveRecord::RecordNotFound": "Shoot, didn't find anything."

Ajax flash message handling

There is also a turboboost:success event that is triggered and passed all current flash messages if they are present:

$(document).on "turboboost:success", (e, flash) ->
  console.log(flash) # -> {'notice': 'Post was successfully created.'}

Scoped response rendering

Turboboost also provides some options for rendering AJAX responses at specific locations in the DOM:

Rails controller render option jQuery function
:within html()
:replace replaceWith()
:prepend prepend()
:append append()
:before before()
:after after()

The value can be any jQuery selector. Example usage:

respond_to do |format|
  format.html
  format.js { render partial: 'task', object: @task, prepend: "#todo-list" }
end

More Repositories

1

apropospriate-theme

A colorful, low-contrast, light & dark theme set for Emacs with a fun name
Emacs Lisp
307
star
2

frog-jump-buffer

The fastest buffer-jumping Emacs lisp package around
Emacs Lisp
158
star
3

ace-jump-buffer

Super fast Emacs buffer switching extension for avy
Emacs Lisp
69
star
4

use-package-ensure-system-package

auto installing system binaries the emacs way
Emacs Lisp
47
star
5

ace-jump-zap

Emacs character zapping, ace-jump-mode style
Emacs Lisp
42
star
6

hoardable

ActiveRecord versioning and soft-deletion with Postgres using uni-temporal inherited tables
Ruby
35
star
7

hemacs

one man's opinionated emacs setup
Emacs Lisp
33
star
8

use-package-chords

key-chord keyword for use-package
Emacs Lisp
23
star
9

org-repo-todo

Simple repository todo management with org-mode
Emacs Lisp
21
star
10

activerecord-exclusive-arc

💫 An ActiveRecord extension for implementing polymorphic relationships as exclusive arcs
Ruby
19
star
11

popup-kill-ring

browse your emacs kill ring in an autocomplete style popup menu
Emacs Lisp
18
star
12

projector.el

lightweight Emacs library for managing project/repository-aware shell and shell command buffers
Emacs Lisp
15
star
13

vscode-todoist

VSCode extension for Todoist
TypeScript
11
star
14

strapi-ruby

Simple Ruby classes for Strapi content types
Ruby
8
star
15

foreman.el

a super simple lisp for running foreman in Emacs
Emacs Lisp
3
star
16

transform-string-at-point

Emacs package for transforming the string at point between camelcase, snakecase, upcase, downcase, etc
Emacs Lisp
1
star
17

director

JavaScript plugin for dynamic template decorating from declarative attributes
CoffeeScript
1
star