Skip to content

Instantly share code, notes, and snippets.

@house9
Created September 29, 2012 15:57
Show Gist options
  • Save house9/3804446 to your computer and use it in GitHub Desktop.
Save house9/3804446 to your computer and use it in GitHub Desktop.
rails asset pipeline - auto invoke javascript based on controller / action
<!--
1) include in layout files after all other javascript includes
2) if you have coffeescript classes that match your controller name - they will be invoked automatically
WARNING: as a general rule don't write js like this with ruby mixed in,
this is one of those rare cases where it 'works' well
-->
<script>
$(document).ready(function () {
var o;
if (window.APP) {
if (window.APP.<%= controller_name.classify %>) {
o = new window.APP.<%= controller_name.classify %>();
if (o.<%= action_name %>) {
o.<%= action_name %>();
} else {
log("NO: window.APP.<%= controller_name.classify %>.<%= action_name %>");
}
} else {
log("NO: window.APP.<%= controller_name.classify %>");
}
}
else {
log("NO: window.APP");
}
});
</script>
# CoffeeScript class maps to controller, methods map to actions
class User
new: ->
@bindForNewUserForm()
create: ->
@bindForNewUserForm() # incase of server side validation rendering new view in create action
profile: ->
# call other re-usable js 'component'
new window.APP.Users.Profile().run()
# bind objects to APP namespace
window.APP ?= {}
window.APP.User = User
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment