Ruby 输出不显示在 sinatra 浏览器上

标签 ruby multithreading sinatra

我想构建一个多线程应用程序。如果我不使用线程,一切正常。当我尝试使用线程时,浏览器上没有显示任何内容。当我使用语法 'puts "%s"%io.read' 时,它会显示在命令提示符上而不是浏览器上。任何帮助将不胜感激。

    require 'sinatra'
    require 'thread'
    set :environment, :production

    get '/price/:upc/:rtype' do
        Webupc = "#{params[:upc]}"
        Webformat = "#{params[:rtype]}"
   MThread = Thread.new do 
        puts "inside thread"
        puts "a = %s" %Webupc
        puts "b = %s" %Webformat
        #call the price
        Maxupclen = 16
        padstr = ""
        padupc = ""
        padlen = (Maxupclen - Webupc.length)
        puts "format type: #{params[:rtype]}"
        puts "UPC: #{params[:upc]}"
        puts "padlen: %s" %padlen
        if (Webformat == 'F')
           puts "inside format"
           if (padlen == 0 ) then
              IO.popen("tstprcpd.exe #{Webupc}") 
                    { |io| 
              "%s" %io.read
            }
           elsif (padlen > 0 ) then
              for i in 1 .. padlen
              padstr = padstr + "0"
              end
              padupc = padstr + Webupc
              puts "padupc %s" %padupc
              IO.popen("tstprcpd.exe #{padupc}") { |io| 
              "%s" %io.read
              }
           elsif (padlen < 0 ) then
              IO.popen("date /T") { |io| 
              "UPC length must be 16 digits or less." %io.read 
              }
           end
        end 
        end
    end

最佳答案

您的代码有几个问题:

  1. 格式不正确
  2. 您正在使用 Uppercase变量名称;这使它们成为常量!
  3. puts不会输出到浏览器,而是输出到控制台。浏览器将收到 block 的返回值,即 block 中最后一条语句的返回值。因此,您需要以不同的方式构建输出(见下文)。
  4. 你永远不会加入话题

这是一个使用线程的最小 sinatra 应用程序。但是,线程在这种情况下没有任何意义,因为在将结果输出到浏览器之前,无论如何都必须等待它终止。为了构建输出,我使用了 StringIO ,您可以将其与 puts 一起使用方便地构建多行字符串。但是,您也可以简单地初始化 res带有 res = "" 的空字符串然后使用 res << "new line\n" 将您的行附加到此字符串.

require 'sinatra'
require 'thread'
require 'stringio'

get '/' do
  res = StringIO.new

  th = Thread.new do
    res.puts 'Hello, world!'
  end

  th.join

  res.string
end

关于Ruby 输出不显示在 sinatra 浏览器上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21293309/

相关文章:

ruby 哈希 : can't convert String into Integer TypeError

javascript - ruby 是否有相当于 javascript 的 Array.prototype.every 方法?

java - Tomcat Chef Recipe 未使用正确的版本

java - 如何重用线程?线程什么时候关闭?

.net - Thread.Start() 与 BackgroundWorker

ruby-on-rails - 发布文件时出现 Ruby 错误 RangeError

ruby - 如何在 Sinatra 中使用 gem?

ruby - Ruby 如何存储大数?

ruby - 可以覆盖/实现的 ruby​​ 运算符列表

multithreading - Lucene如何在多线程环境下使用IndexReader?