2

In my rails app, HTML is rendered before controller completely runs. I want index method in controller to first run completely before rendering HTML. I was able to achieve this by adding <% sleep(x) %> at the beginning of the HTML page but i want to do it without using it. can anyone suggest a way to accomplish this?

Thanks

Abhinav Kulkarni
  • 223
  • 3
  • 10
  • Can you paste def index action code – Neeraj Jun 09 '14 at 11:38
  • Erm, do you mean you want the action method on your controller to do something after it's rendered the page? – Tony Hopkinson Jun 09 '14 at 11:39
  • no i want index method to execute before rendering the pagedef index @data=Csvtest.all @length=@data.length-1 @resp=[] threads = (0..@length-1).map do |i| #services are pinged concurrently Thread.new(i) do |i| @resp[i]=%x{curl -sL -w "%{http_code}" #{@data[i]['url']} -o /dev/null}.to_i #@response contains status code end end end – Abhinav Kulkarni Jun 09 '14 at 11:42
  • sry about indentation – Abhinav Kulkarni Jun 09 '14 at 11:43
  • i want this method to finish before rendering the page – Abhinav Kulkarni Jun 09 '14 at 11:44
  • i am using @resp in my html page and it using nil value – Abhinav Kulkarni Jun 09 '14 at 11:46
  • You can't do this. The page is rendered INSIDE the action: that's what the action does - it runs a bit of code (the code you can see in your action) and then renders the page. The rendering happens inside the action. I think you need to take a step back and explain why you want to do this. – Max Williams Jun 09 '14 at 11:54
  • U r making curl request in controller. Better do it via ajax (after rendering page) and show loader till response comes. – Neeraj Jun 09 '14 at 11:54
  • @Neeraj It depends on the endpoint of his curl, if it is not on his current domain. There is a problem with cross-origin policy in the ajax call. You can find more here http://stackoverflow.com/questions/3076414/ways-to-circumvent-the-same-origin-policy – edariedl Jun 09 '14 at 12:08

1 Answers1

1

From the comment above you are using this index action:

def index 
  @data=Csvtest.all
  @length=@data.length-1 
  @resp=[] 
  threads = (0..@length-1).map do |i| #services are pinged concurrently 
    Thread.new(i) do |i| 
      @resp[i] = %x{curl -sL -w "%{http_code}" #{@data[i]['url']} -o /dev/null}.to_i #@response contains status code 
    end 
  end 
end

You are forgetting to say main thread to wait before all other threads terminates. You should call

threads.each { |t| t.join }

It tells, main thread wait until all of concurrent threads will pass to the end and than continue.

edariedl
  • 3,234
  • 16
  • 19