Skip to content

Instantly share code, notes, and snippets.

@alcedo
Last active August 29, 2015 14:00
Show Gist options
  • Select an option

  • Save alcedo/11391217 to your computer and use it in GitHub Desktop.

Select an option

Save alcedo/11391217 to your computer and use it in GitHub Desktop.
Rails with page specific JS compiled from various sites
<% # app/views/page/contact.html.erb %>
<h1>Contact</h1>
<p>This is the contact page</p>
<%= javascript_tag do %>
alert("My example alert box.");
<% end %>
JS:
app/assets/javascripts/alert.js
alert("My example alert box.");
erb:
<%# app/views/page/contact.html.erb %>
<%= javascript_include_tag "alert" %>
<h1>Contact</h1>
<p>This is the contact page</p>
config:
# config/environments/production.rb
config.assets.precompile += %w( alert.js )
erb:
<%# app/views/layouts/application.html.erb %>
<body class="<%= controller_name %> <%= action_name %>">
<%= yield %>
</body>
outputs:
<body class="pages contact">
...
</body>
JS:
insert https://raw.githubusercontent.com/Verba/jquery-readyselector/master/jquery.readyselector.js
// app/assets/javascripts/alert.js.coffee
$(".pages.contact").ready ->
alert "My example alert box."
we can further include rails objects into the html hidden dom. eg:
# views/players/index.html.erb
<%= content_tag :div, class: "players_class", data: {players: @players} do %>
<% end %>
uses a plugin: https://github.com/kbparagua/paloma
scroll down to Passing Parameters section
JS: # assets/javascripts/players.js
var Players = {
randomPlayer : function(players) {
var min = 0;
var max = players.length - 1;
var random_index = Math.floor(Math.random() * (max - min + 1)) + min;
return players[random_index];
},
alertRandomPlayer : function(players) {
var random_player = this.randomPlayer(players);
alert("Name: " + random_player.name + " :: Batting average: " + random_player.batting_average);
}
}
erb:
# views/layouts/application.html.erb
# Add this line to the head tag:
<%= yield :head %>
# views/players/index.html.erb
<% content_for :head do %>
<script type="text/javascript">
<%= render 'players/alert_random_player.js' %>
</script>
<% end %>
# views/players/_alert_random_player.js.erb
$(function() {
players = $('.players_class').data('players');
Players.alertRandomPlayer(players);
});
//store ruby vars in dom:
# views/players/index.html.erb
<%= content_tag :div, class: "players_class", data: {players: @players} do %>
<% end %>
sources:
http://brandonhilkert.com/blog/page-specific-javascript-in-rails/
http://codequizzes.wordpress.com/2013/06/06/rails-javascript-workflow-rendering-javascript-partials/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment