Skip to content

Instantly share code, notes, and snippets.

@benphelps
Last active September 9, 2020 22:14
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benphelps/dccde4d11370511f0d64be6563796fda to your computer and use it in GitHub Desktop.
Save benphelps/dccde4d11370511f0d64be6563796fda to your computer and use it in GitHub Desktop.
Action Specific Javascript for Rails 5

Action Specific Javascript for Rails 5

This is a simple example of action specific javascript. It also allows you to pass data to JS from inside rails controllers. Works with Turbolinks 5 (not required).

Installation

Add the files below to your project, then insert <%= insert_javascript_hook %> somewhere in the footer of your layout.

You'll need these gems:

gem 'jquery-rails'
gem 'jquery-turbolinks' # Only if you use Turbolinks
gem 'turbolinks', '~> 5.0.0' # Only if you use Turbolinks

Example

# Somewhere in your JS stack
Javascript.controller 'Dashboard', index: ->
  console.log this.params.test.some_value
# You can pass values to JS from Rails
class DashboardController < ApplicationController
  def index
    js test: { some_value: 'Hello from Rails!' }
  end
end
<!-- app/views/layouts/_javascript.html.erb -->
<script type="text/javascript">
Javascript.rails = JSON.parse("<%= json %>");
Javascript.start();
</script>
# app/javascripts/application.coffee
# jQuery
#= require jquery
#= require jquery_ujs
# Turbolinks, optional
#= require jquery.turbolinks
#= require turbolinks
#= require turbolinks-compatibility
# You can now include your Javascript controllers.
# app/javascripts/application.coffee.rb
class JavascriptController
controllers: {}
rails: {}
controller: (controller, actions) =>
@controllers[controller] = { } unless @controllers[controller]
for action, callback of actions
@controllers[controller][action] = callback
start: ->
return unless @rails.controller && @rails.action
method = "#{@rails.controller}##{@rails.action}"
callback = @controllers[@rails.controller]?[@rails.action]
if callback
callback.call(@rails)
console.log "Loading Javascript for #{method} with these params:", @rails.params
else
console.log "No Javascript for #{method}"
@Javascript = new JavascriptController()
# app/helpers/javascript_helper.rb
module JavascriptHelper
def js(objects = {})
objects.each do |key, value|
js_object[:params][key] = value
end
end
def insert_javascript_hook
render 'layouts/javascript', json: escape_javascript(js_object.to_json.html_safe)
end
private
def js_object
params = request.params
@js_object ||= {
controller: params[:controller].camelize,
action: params[:action],
params: {}
}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment