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?
-
1Javascript is a runtime environment on the browser (client side). I assume that your server side environment is Rails which is a different runtime environment (server side). The client makes requests to the server side using the HTTP protocol. When you say "call ruby from a javascript function" what you are essentially wanting to do is "make an AJAX call from the browser to do a database operation on the server side". Once you understand this interaction, you will be able to search the right place and get appropriately relevant answers IMHO.Aditya Sanghi– Aditya Sanghi2012年07月27日 08:18:24 +00:00Commented Jul 27, 2012 at 8:18
4 Answers 4
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)
3 Comments
I think it is not possible, there are some reasons:
- Browsers don't support Ruby
- JavaScript and Ruby have different system of types and I don't know any interface between them
- Also you cannot place JavaScript code and Ruby code in one file, because there is no mime type for such file
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.
Comments
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.
2 Comments
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 %>
Comments
Explore related questions
See similar questions with these tags.