Daniel Sheard Daniel Sheard - 20 days ago 4x
Ruby Question

Call JavaScript function from Ruby on Rails model

I have built a Rails app that has an API that returns a JSON object. I want to allow users to write their own scripts and store them. These scripts will then be executed when the user makes an API call to the app and injected as part of the response.

An example would be when a user calls my API, their javascript would be called and whatever is returned from their script would be saved as a string and used by one of my models and used as part of the JSON object - not the full response.

I want to know how to call a javascript function from a rails model, save the output of the javascript as a string in Ruby, and then be able to process whatever is returned before making the API response.

The current answers seem to only be related to the controllers and rendering as JS, but I would like to execute the script from the model.

It should be something like:

string = execute_javascript("return 'hello world';")

This is more related to pure Ruby than Rails as I am just wanting to call it from a standard Ruby class and save the output as a string. I also need to consider the security implications of doing this, but first would like to know how to do it


The simplest solution to execute most common Javascript code is using ExecJS gem. If you are using the Rails standard gem bundle then ExecJS is already included with Rails Coffeescript. A short example:

require "execjs"
ExecJS.eval "'red yellow blue'.split(' ')"
# => ["red", "yellow", "blue"]

The above solution is only good if you are running a prototype. In production, you would want to somehow run the user code in sandbox and preferably on the whole different server. You would also need to ensure the code won't take 100% resource of your server while executing and screen the code to ensure it won't do anything malicious.