2

I've got a ruby script run-this.rb that outputs live calculations to a text file when I run

ruby run-this.rb > output.txt

However, I need to load this same procedure onto a web server where the Ruby script will run on page load and the web page will read the result from the txt file.

My question is two part,

1) How do you tell the web page to run this script on load?

and

2) How do I output the results of run-this.rb to output.txt on page refresh?

Thanks!

1 Answer 1

6

You can build a simple web application with the Sinatra framework that will

  • Run your script
  • Save the output in a variable
  • Write the variable contents to a file
  • Then also write the variable contents to a HTTP response

I would however advise you to encapsulate your script in a Ruby class, which makes it easier to run from another file. For example, in 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

In the same directory, you can now have a second file server.rb, which will perform the steps outlined in the list above:

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

After installing Sinatra with gem install sinatra, you can start the server with ruby server.rb. The output will tell you where to point your browser:

[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

This means your page is now available at http://127.0.0.1:4567, so go ahead and type this in your browser. Et voilá!

screenshot of browser with above page

After you have displayed the page, the directory will also contain output.txt with the same contents.

Sign up to request clarification or add additional context in comments.

3 Comments

seriously one of the best answers i've seen in a while +1
+1.. I just started reading Sinatra.. You made my interest level 2 times than now.. :)
This is probably the best answer i've ever got on a question here. Thanks! +1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.