Naarsh Naarsh - 4 months ago 5x
Ajax Question

[RAILS][Javascript] Is it "clean" to use controller variables in javascript ?

I'm having a little question about convention and bests ways of doing things in rails.

Right now for a view I need to get an array of hash that I can construct way easier in my controller. I need this arry for my javascript code...

So I far i found a solution that isn't an ajax request which is this one :

var toto = #{@controller_var.to_json}

I know that it's probably "better" of doing an ajax request or to store this variable in erb code... But I try to limit myself to do ajax requests (since this page already does a few ones) and I dislike creating hidden field to store my controller method...

Anyway, if you could give your opinion/advices on this I would really apreciate it ! :)

Best regards !


The primary problem with this approach is that your javascript is now tightly coupled with rails and it can not be tested in isolation without a full rails server running.

I totally avoid server generated javascript for this reason.

Even if you don't go the full way and build an API driven client application, the least you can do is to inject the JSON in a dom element:

<script id="toto" type="application/json">
  <%= @controller_var.to_json %>

Now in your test cases you can use a static HTML page where the script can contain mock data.

Another problem is that you can not serve server generated javascript through a CDN. This is not a problem if your js responses are very small but now to interact with the javascript existing on the page you will most likely resort to global variables.

Besides the obvious issues with global variables leading to less maintainable code, the extent to which minifiers and optimizers can perform dead code elimination suffers significantly.