Sinatra executing ls on sever side

67 Views Asked by At

I am trying to show in Chrome using Sinatra, the result of ls. But the explorer gets in an "Connecting..." loop.

My code is:

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

I am not sure of that puts, I think that maybe is not the apropiate method. What could be happening and how can I solve it?

PS: In the explorer I used localhost.com:4567/

2

There are 2 best solutions below

0
On

As @pgblu pointed out you should use backticks. https://stackoverflow.com/a/18623297/1279355

And the second thing, puts print the result only to your shell/log, but to see the result in your chrome you need either:

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

or

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

As you can see the return is optional, if there is no return Sinatra just displays the last variable/operation.

0
On

Use the backticks ( ` ) instead of the Kernel#exec command. The former returns a string that you can then use in your ruby process. The latter throws your execution context into a new process and has no return value.

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

Note that the call to puts will not look very nice and that you'll probably want to format it or parse/manipulate it further. But at least you'll get something you can use.