Multiple Body Flow Using Asynchronous Sinatra

I would like to start a long polling request from javascript, which is good, and I expect my ruby ​​prose to pass multiple sections of the body into javascript. Why doesn't the following (pseudo) code work?

require 'rubygems'
require 'sinatra/async'
require 'eventmachine'
require 'thin'
require 'json'

    class Test < Sinatra:Base
      register Sinatra::Async

      aget '/process' do
        for c in 1..10
          body {
            { :data => [ "this is part #{c}" ] }.to_json
          end
        end
      end

      run!
    end

Maybe I misunderstood what a long survey and asink should do, but I expect that I will receive several bodies sent back to the client? Do I need to use eventmachine or something else?

thank

+3
source share
2 answers
require 'rubygems'
require 'sinatra/async'
require 'thin'
require 'json'

class Test < Sinatra::Base
  register Sinatra::Async

  class JSONStream
    include EventMachine::Deferrable

    def stream(object)
      @block.call object.to_json + "\n"
    end

    def each(&block)
      @block = block
    end
  end

  aget '/process' do
    puts 'ok'
    out = JSONStream.new
    body out
    EM.next_tick do
      c = 0
      timer = EM.add_periodic_timer(0.3) do
        c += 1
        out.stream :data => ["this is part #{c}"]
        if c == 100
          timer.cancel
          out.succeed
        end
      end
    end
  end

  run!
end

See also: http://confreaks.net/videos/564-scotlandruby2011-real-time-rack

+6
source

, EventMachine, . . .

require 'sinatra/async'

 class AsyncTest < Sinatra::Base
   register Sinatra::Async

   aget '/' do
     body "hello async"
   end

   aget '/delay/:n' do |n|
     EM.add_timer(n.to_i) { body { "delayed for #{n} seconds" } }
   end

 end
+1

Source: https://habr.com/ru/post/1791381/


All Articles