2014-01-08 133 views
2

我已经得到了实时计算输出到,当我运行页面上运行Ruby脚本刷新

ruby run-this.rb > output.txt

不过,我需要加载此相同的程序到web服务器上的文本文件的Ruby脚本run-this.rb Ruby脚本将在页面加载时运行,并且网页将从txt文件读取结果。

我的问题是两个部分,

1)你怎么知道网页上运行负荷此脚本?

2)如何输出的run-this.rboutput.txt页面上的成绩刷新?

谢谢!

回答

6

你可以建立一个与Sinatra framework一个简单的Web应用程序,将

  • 运行脚本
  • 保存在一个变量
  • 输出写变量内容到一个文件
  • 然后还写HTTP响应的可变内容

但是,我会建议你封装在Ruby类中吃了你的脚本,这使得从另一个文件运行起来更容易。例如,在run-this.rb

class FooRunner 
    def self.run! 
    # write to string instead of printing with puts 
    result = '' 

    # do your computations and append to result 
    result << 'hello, world!' 

    # return string 
    result 
    end 
end 

# maintain old functionality: when running the script 
# directly with `ruby run-this.rb`, simply run the code 
# above and print the result to stdout 
if __FILE__ == $0 
    puts FooRunner.run! 
end 

在同一目录中,你现在可以有第二个文件server.rb,将执行在上面的列表中列出的步骤:

require 'sinatra' 
require './run-this' 

get '/' do 
    # run script and save result to variable 
    result = FooRunner.run! 

    # write result to output.txt 
    File.open('output.txt','w') do |f| 
    f.write result 
    end 

    # return result to be written to HTTP response 
    content_type :text 
    result 
end 

gem install sinatra安装西纳特拉后,您可以使用ruby server.rb启动服务器。输出将告诉你在哪里浏览器指向:

[2014-01-08 07:06:58] INFO WEBrick 1.3.1 
[2014-01-08 07:06:58] INFO ruby 2.0.0 (2013-06-27) [x86_64-darwin12.3.0] 
== Sinatra/1.4.4 has taken the stage on 4567 for development with backup from WEBrick 
[2014-01-08 07:06:58] INFO WEBrick::HTTPServer#start: pid=92108 port=4567 

这意味着您的页面现已在http://127.0.0.1:4567,所以继续前进,在浏览器中键入此。 Etvoilá!

screenshot of browser with above page

你已经显示的页面后,该目录还包含output.txt具有相同的内容。

+0

认真的一个我曾经见过的最好的答案+1 – sunnyrjuneja

+0

+1 ..我刚开始阅读* Sinatra * ..你让我的兴趣水平比现在的2倍.. :) –

+0

这可能是我在这里遇到过的最佳答案。谢谢! +1 – Newtt

相关问题