0

Getting timeout exception when trying to access web page. In controller method or in helper method trying to get content of local url:

require 'open-uri'
data = JSON.load(open('http://0.0.0.0:3000/notebookcheck/cpus.json'))

As a result getting timeout error. If i run this code in irb it would work.

How can i correctly get content of local url in rails?

ambi
  • 35
  • 1
  • 1
  • 9
  • i am a little skeptical if you would need "http://0.0.0.0:3000" . did you check the log and see whether rails gets the file? – argentum47 Oct 27 '14 at 07:54
  • it fails while trying to open('http://0.0.0.0:3000/notebookcheck/cpus.json') – ambi Oct 27 '14 at 08:20

2 Answers2

1

Intuition:

This is happening because requests are being handled sequentially.

Say you have two requests. One is to view page A, and the other is to view page B.

However, the request to view page B cannot be fulfilled until viewing page A is done.

In your case, you created a dependency: page A cannot finish rendering until page B renders. However, page B won't render until all previous requests (in this case, the request to render page A) are completed.

In short, completing the read request depends on the requested page loading.

What's happening here:

Your request to render the JSON cannot finish until the original request is complete - so the process hangs.

Eventually, it waits too long and just times out.

This happens because unlike other languages (e.g. Javascript), Ruby requests are blocking when run on a single thread (i.e. synchronous, as opposed to asynchronous).

Solution:

Note that if you were running multiple processes or threads, this would work. See this SO answer..

Instead of spawning threads, however, you could just render the file directly to string with the render_to_string method in Rails.

Good luck.

Community
  • 1
  • 1
Yuval Karmi
  • 26,277
  • 39
  • 124
  • 175
0

I think you need to add .read after opening the file:

require 'open-uri'
data = JSON.load(open('http://0.0.0.0:3000/notebookcheck/cpus.json').read)
Nimir
  • 5,727
  • 1
  • 26
  • 34