Ruby on Rails – Send JavaScript variable from controller to external Javascript asset file

Yes, you can!

Rewrite your JS code into function with one argument (timelimit) and put it into some external file. Then you can call the function from view and pass that @timeleft variable as JS function argument.

Short example:

@time_left = - 3.hours.to_i


function count_down(time_left) {


<%=javascript_tag "count_down(#{@time_left})" -%>


Example not tested, it is only idea not complete solution. Don’t forget to load that JS file. You can use other JS rails helper javascript_include_tag.

Leave a Comment