2015-06-15 115 views
1

我試圖在Chrome中使用Sinatra顯示,結果爲ls。但是資源管理器進入「連接...」循環。Sinatra在服務器端執行ls

我的代碼是:

require 'rubygems' if RUBY_VERSION < "1.9" 
require 'sinatra/base' 

#This is the webservice to launch the gamma project 
#Using Request at the principal webpage 
class MyApp < Sinatra::Base 
    get '/' do 
    result = exec "ls" 
    puts result 
    end 
end 

我不知道該puts的,我想,也許是不apropiate方法。會發生什麼,我該如何解決?

PS:在資源管理器我用localhost.com:4567/

回答

0

使用反引號(`)代替內核#exec命令。前者返回一個字符串,然後你可以在你的ruby進程中使用。後者將您的執行上下文引入新進程並且沒有返回值。

get '/' do 
    result = %x`ls` 
    puts result 
end 

注意,調用puts不會看起來非常漂亮,你可能會想格式化或解析/進一步操縱它。但至少你會得到一些你可以使用的東西。

0

由於@pgblu指出你應該使用反引號。 https://stackoverflow.com/a/18623297/1279355

第二件事,puts打印結果只有你的shell /日誌, 而是看你需要或者結果在您的Chrome:

get '/' do 
    result = %x`ls` 
    return result 
end 

get '/' do 
    result = %x`ls` 
    result 
end 

正如你可以看到返回是可選的,如果沒有返回,Sinatra只顯示最後一個變量/操作。

相關問題