【问题标题】:Ruby output is not displayed on the sinatra browserRuby 输出不显示在 sinatra 浏览器上
【发布时间】:2014-01-23 17:46:51
【问题描述】:

我想构建一个多线程应用程序。如果我不使用线程,一切正常。当我尝试使用线程时,浏览器上没有显示任何内容。当我使用语法 '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

【问题讨论】:

  • 如果您要提交大量代码并希望其他人阅读,则需要正确格式化该代码。

标签: ruby multithreading sinatra


【解决方案1】:

你的代码有几个问题:

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

这是一个使用线程的最小 sinatra 应用程序。但是,在这种情况下,线程毫无意义,因为无论如何您都必须等待它的终止,然后才能将结果输出到浏览器。为了构建输出,我使用了StringIO,您可以使用puts 方便地构建多行字符串。但是,您也可以简单地使用 res = "" 使用空字符串初始化 res,然后使用 res &lt;&lt; "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

【讨论】:

    猜你喜欢
    • 2021-01-14
    • 2018-08-09
    • 1970-01-01
    • 2016-12-18
    • 2012-08-05
    • 1970-01-01
    • 1970-01-01
    • 2011-03-04
    • 2014-10-21
    相关资源
    最近更新 更多