JY Choi
JY Choi

Reputation: 53

Can I delay HTTP response in rails?

I'm new in Rails 4. I want to delay HTTP response.

I thought the 'respond_to' method is enable to respond to HTTP request.

However, When I removed the 'respond_to' method, The rails controller automatically responded to request.

Below is my step for this.

  1. Send HTTP Request in view

    [index.html.erb]
    <script>
    var ready = function() {
        alert('this is function');
    }
    var aquery = function() {
        $.ajax({
            type : "POST",
            url : "app/subaction",
        });
    }
    
    $(document).on('ready page:load', aquery); 
    </script>
    
  2. Receive HTTP Request in Controller

    class AppController < ApplicationController
       def subaction
         (Nothing here...)
       end
    end
    
  3. subaction.js.erb

    $('#div_id').empty().append("Complete response ...");
    

In this step, response was executed automatically although there is not "respond_to" method.

Can I delay the response ??? Can you explain request-response operation in rails ?

Thank you...

Upvotes: 1

Views: 2683

Answers (1)

Alex P
Alex P

Reputation: 6072

The main reason Rails renders a response by default is because the documentation says so. Rails follows a philosophy of 'convention over configuration', which means it tries to help you out in ways that keep the code you write to a minimum. Most of the time you want your controller actions to render a view, so Rails does that for you.

You can use a number of techniques to delay responses. The simplest is to use Ruby's sleep method to introduce a delay:

class AppController < ApplicationController
   def subaction
     sleep 3 # Wait for 3 seconds before responding
   end
end

This might be useful when testing how your app behaves over a slow internet connection, but should probably be avoided in production code. Fast apps make happy users.

You could also use the ActionController::Live module, introduced in Rails 4.0.2. It allows you to stream data to the client, but consuming the stream can be tricky. jQuery waits for the response to complete before firing callbacks, so you'll have to use something else to process the stream.

This is similar to Websockets, an emerging streaming standard. There's some support available for websockets in Rails, but it's not universally supported by browsers.


Another alternative is to switch the delay to the frontend. You can use JavaScript's setTimeout or setInterval to call some code after a delay:

setTimeout(function() { 
    alert("I run once, after 4 seconds");
}, 4000);
setInterval(function() { 
    alert("I run every two seconds");
}, 2000);

If you're trying to check for updates, you might be tempted to use setInterval, but you may find it more flexible to use setTimeout to schedule a one-off check of the server. You can then include a time delay from the server which specifies how long to wait before asking again.

Upvotes: 1

Related Questions