2

I have a single controller that has 2 actions/views and a channel all of which have been scaffolded and pretty much using a default project.

When I load either view I can see that the channel subscribes properly.

I need the subscription to happen only on one of the views. Currently the asset pipeline appears to be compiling everything into a single js file and then serving that js file to every page.

When I scaffolded my channel it created some javascript called channel.js. How can I include channel.js with only specific actions/views?

Ashish Jambhulkar
  • 1,374
  • 2
  • 14
  • 26
Jamesla
  • 1,378
  • 7
  • 31
  • 62
  • 1
    Possible duplicate of [Asset pipeline: use javascript files for only one controller](https://stackoverflow.com/questions/19899542/asset-pipeline-use-javascript-files-for-only-one-controller) – Gerry Aug 11 '17 at 13:25
  • Did any of the answers for this question fix your problem? – Jake Jun 14 '18 at 20:10

2 Answers2

2

The asset pipeline indeed compiles everything into a single JS file, so there is no built-in way to limit the execution of certain JavaScript files to specific actions.

There is a way to solve this, however. First, add this helper method to application_helper.rb:

# application_helper.rb
def body_classes(*args)
  return (@body_classes || []).join(" ") if args.empty?
  @body_classes ||= []
  @body_classes += args.map { |klass| klass.to_s.gsub("_", "-") }
  @body_classes.uniq!
  nil
end

And use it in your layout:

<!-- application.html.erb -->
<body class="<%= body_classes %>">
  <!-- ... -->
</body>

With this, you can specify certain body classes in your templates, to be added to the <body> tag:

<!-- your_action.html.erb -->
<%= body_classes :my_custom, :action_class %>
<h1>Your action</h1>
<!-- ... -->

The code above will add the following classes to <body>:

<body class="my-custom action-class">

Finally, you can test for these body classes in your JS code:

// your_action.js
if($("body").hasClass("my-custom")) {
  // run code specific to pages with the 'my-custom' class
}
Mate Solymosi
  • 5,699
  • 23
  • 30
1

Try going into your controller that holds the method to the view you want to have the javascript incorporated in and write this inside:

def 'the view you want to effect' # This could be "index" for your index.html.erb view
  @java = "channel.js"
end

Then in the following file, locate your <%= javascript_include_tag %>

views > layout > application.html.erb

Include this into your tag to load a different javascript file for any view you want with the previous process. (Try it with CSS inside your CSS include tags too.)

<%= javascript_include_tag '#{@java}' %>
Jake
  • 1,086
  • 12
  • 38