public
Created

Conditionally Execute JavaScript in the Asset Pipeline

  • Download Gist
Gemfile
Ruby
1 2
# https://github.com/gazay/gon
gem 'gon'
application_controller.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11
class ApplicationController < ActionController::Base
before_filter :set_gon
 
# ...
 
private
def set_gon
gon.page = "#{params[:controller]}_#{params[:action]}"
end
end
end
foo.js.coffee
CoffeeScript
1 2 3 4 5 6 7
if gon.page is 'foo_bar'
$ ->
alert "Top o' the mornin' to ya'!"
 
if gon.page is 'foo_baz'
$ ->
alert "... and Bob's your uncle!"
layout.html.haml
Haml
1 2 3 4 5 6 7
!!! 5
%html
%body
%h1 Foo
= yield
= include_gon
= javascript_include_tag 'application'

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.