I have written a ruby function and want to place it in js file, the js function should be able to give a call to ruby function and store the return value.
Is it possible? How to do this task?
I have written a ruby function and want to place it in js file, the js function should be able to give a call to ruby function and store the return value.
Is it possible? How to do this task?
The Implementation you need depends on when are you calling the ruby code or function
Is is while building or rendering a page or js?
Then you can you use the js with .erb extension .(as suggested by Super engineer) This allows you to call any ruby code and function available in views and application helpers.
eg demo.js.erb
var arr = "<%= call_function %>"
You need the function from client side? Then it is impossible to call the function directly, You need to use ajax for such scenarios. (as suggested by Spernsky Danil)
I think it is not possible, there are some reasons:
So I suppose you should convert your Ruby function to JavaScript funciton.
Or you may implement your Ruby function as a part of the Server API and call it from JavaScript by Ajax.
JavaScript is a client-side language and Ruby is a server-side language, they can't call each other directly, use AJAX or WS instead for communicating between server and client sides.
Well you can have js.erb file. In which you can include ruby code. Just take a look at this code snippet from my project.
$("#myModal").modal('hide');
<% if @status == "ok" %>
<%= add_gritter("We will contact you as soon as possible!", :image => :success, :class_name => "gritter-light") %>
<% else %>
<%= add_gritter("Something went wrong while saving you request. Please try again!", :image => :error, :class_name => "gritter-light") %>
<% end %>