A
A
Alexey Chernysh2015-09-21 12:15:00
JavaScript
Alexey Chernysh, 2015-09-21 12:15:00

Rails 4 asset pipeline - how to set scopes?

I have two controllers in my Rails 4 project, let's call them c1 and c2 for short.
The "assets/javascripts" folder contains c1.js and c2.js, respectively, containing some functions. Some of the functions have identical names but different behavior, for example, the getXPath() function exists in both c1.js and c2.js. This leads to problems, since a function from c2.js can be called from c1 view.
You can of course name functions with controller names, like getXPathC1() / getXPathC2() , but I would prefer to set the scopes so that only c1.js is available in the c1 view and only c2.js is available in the c2 view.
How can I do that? Is this even possible?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
vsuhachev, 2015-09-21
@vsuhachev

common.js

M
malroc, 2015-09-21
@malroc

If you are guaranteed not to need javascript from c2 in controller c1 and vice versa, create two different compiled javascript files instead of one (application.js), or simply exclude c1.js and c2.js from application.js and include them separately later ( the second method is less labor-intensive, but the number of get-requests increases, because there will be 2 included js files per controller - application.js and c1/2.js).
In both cases, for the production environment, you will need to change the asset compilation settings (because by default only application.js remains in public access).

J
jarosluv, 2015-09-22
@jarosluv

3 ways to solve your problem:
theflyingdeveloper.com/controller-specific-assets-...
https://stackoverflow.com/questions/6571753/rails-...
https://railsapps.github.io/rails-javascript- inclu...
Although, in essence, they all boil down to one thing, the only difference is how you will determine the required js file to connect - automatically by the name of the controller, indicating the name of the desired file in the views, or by defining the functions needed for the page in the js itself -code.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question