Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

web-workers in Rails projects

I try to use web workers to be able to run several javascript codes at the same time. To start the worker I put the following into my javascript code section:

var worker = new Worker("my_task.js");
worker.onmessage = function(e) {
    console.log('Worker said: ', e.data);
};
worker.postMessage("test"); 

my_task.js is the same folder as the file that holds the code above. This is how my_task.js looks like:

self.addEventListener('message', function(e) {
  self.postMessage(e.data);
}, false);

But there seems to be a problem with Ruby on Rails (version 3.2.1):

Started GET "/users/my_task.js" for 127.0.0.1 at ...
...
...
ActiveRecord::RecordNotFound (Couldn't find User with id=my_task)

As you can see Rails tries to send an http get request when the script is started.
How can I solve this problem? Is there a better way to use web workers in Rails projects?

Thanks

like image 880
zobel Avatar asked Feb 19 '13 11:02

zobel


People also ask

What can you do with web workers?

Web Workers are a simple means for web content to run scripts in background threads. The worker thread can perform tasks without interfering with the user interface.

What are web workers example?

Common examples of web workers would be: Dashboard pages that display real-time data such as stock prices, real-time active users, and so on. Fetching huge files from the server.

How many web workers can run concurrently?

A web worker is a JavaScript program running on a different thread, in parallel with main thread. The browser creates one thread per tab. The main thread can spawn an unlimited number of web workers, until the user's system resources are fully consumed.

What are the restrictions of web workers on DOM?

Limitations Of Web Workers The Web Workers API is a very powerful tool, but it has a few limitations: A worker can't directly manipulate the DOM and has limited access to methods and properties of the window object. A worker can not be run directly from the filesystem. It can only be run via a server.


1 Answers

  • Put my_task.js in /public/javascripts
  • In your javascript code where the worker is created, use the following ERB: var worker = new Worker("<%= javascript_path "my_task.js" %>");
  • Add .erb to the extension of whatever file the above javascript code is found in. So if it's mypage.js, it becomes mypage.js.erb.

The above works for me on Rails 4.2.0, ruby 2.0.0p598

like image 58
evdc Avatar answered Nov 07 '22 06:11

evdc