Last active
July 4, 2017 22:59
-
-
Save acolin/3ecf1ef690d8d937696558a7883ee9c5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// in the Gemfile | |
gem 'handlebars_assets' | |
// in hb_helpers.js.coffee | |
Handlebars.registerHelper 'humanize', (str) -> | |
str.replace(/_/g, ' ') | |
// application.js | |
//= require jquery | |
//= require jquery_ujs | |
//= require turbolinks | |
//= require handlebars.runtime | |
//= require hb_helpers | |
//= require_tree ./templates | |
//= require_tree . | |
//coffescript file i.e. form_errors.js.coffee | |
window.FormErrors = do -> | |
# Private methods | |
_displayErrors = (container, response) -> | |
compiledView = HandlebarsTemplates['shared/form_errors'](response) | |
container.html(compiledView) | |
container.show() | |
# Public methods | |
init: (params={}) -> | |
onError = params.onError | |
onSuccess = params.onSuccess | |
form = $("##{params.formId}") | |
errorsContainer = $("##{params.errorsContainerId}") | |
form.on("ajax:success", (e, data, status, xhr) -> | |
onSuccess(data) if (typeof onSuccess is 'function') | |
).on("ajax:error", (e, xhr, status, error) -> | |
onError(xhr.responseJSON) if (typeof onError is 'function') | |
_displayErrors(errorsContainer, xhr.responseJSON) | |
) | |
// using handlebars template | |
// i.e. /templates/form_errors.hbs | |
<ul> | |
{{#each errors as |msgs attr|}} | |
{{#each msgs as |msg|}} | |
<li>{{humanize attr}}: {{msg}}</li> | |
{{/each}} | |
{{/each}} | |
// in the view .html.erb | |
<% content_for :bottom_js do %> | |
<script type="text/javascript"> | |
$(function(){ | |
FormErrors.init({ | |
formId: "activate-account-form", | |
errorsContainerId: "form-errors", | |
onSuccess: function(data) { | |
window.location.href = "<%= orders_url %>" | |
} | |
}); | |
}); | |
</script> | |
<% end %> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment