Accessing a "helper" method "foo" defined in a controller, in a .js file

Hello.

I am having some trouble accessing a method “foo” I defined in a controller.

I was under the impression that if “foo” is in the controller that renders bar.html.erb, then bar.html.erb can in fact see a method in this controller provided I put the “helper_method: foo” notation in the controller. I was able to verify that foo was in fact accessible in the bar.html.erb file.

The problem is I want to access foo in alpha.js.erb. My application.js includes alpha.js (alpha.js.erb) implicitely because alpha.js.erb is in the app/assets/javascripts and application.js has “//= require_tree .”.

But alpha.js.erb cannot see foo. I have no idea how to get my custom ruby functions to become accessible in the js files.

Would appreciate help. I scoured google for a few hours already and could not find much on this.

Thanks.

Hi Neeraj,

You most serious problem you are facing is that js files included in application.js are not rendered in the context of your request. They are meant to be precompiled (meaning when you deploy your application they are all compiled only once so that each request for them is very fast) and loaded separately.

There are a couple of ways around this, the easiest being adding a javascript block to your application.html.erb or bar.html.erb that renders that code instead. Another alternative would be to have your javascript call an API for that data.

If you aren’t trying to render request-specific data there are other alternatives. Is that the case?

Hi Daniel.

Thanks very much for the response. The fact that they are precompiled at deployment might explain why I have been finding it excruciatingly hard to figure this out.

If I went with the approach of adding a JS block into my html.erb file, it would be slower, I suspect. But would it mean that all my helpers in rubyland are now namespace visible? Now if I do this, wouldn’t I have to move the js file in question out of the folder that application.js is including all js files from?

My second question is probably more important. The logic needed in the helper that I need in this js file is logic that is available right at precompilation time. I know that .js.erb files can in fact use helpers, so how does that work? Are these limited to js.erb files that are not precompiled, or can precompiled ones also include “special” helpers that are “executed” at precompilation time? Ideally, application.js is precompiled and this helper is run at precompilation. If that’s possible.

Thanks!

Oh, and I am not rendering request-specific data. To put it more directly, the data needed in this helper is in a database table. I just need to look it up in the table and then do some stuff related to it in the js file. I can do this right at precompile time. What alternatives are there?