John Doe
John Doe

Reputation: 11

Controlling a Ruby script from the web

I have a simple script written in Ruby that can start and stop an executable. I would like to have two buttons on a simple web page, start and stop, and execute the code on the machine the page is hosted from. What would be the easiest/lightest way of doing it?

Upvotes: 0

Views: 99

Answers (1)

VB.
VB.

Reputation: 484

I would suggest using Sinatra for such a small tasks. Let's start with Gemfile, if you're using bundler:

source 'https://rubygems.org'
gem 'sinatra'
gem 'slim'

Then just run "bundler install" or just install these gems manually. Let's write our tiny web server, create myapp.rb with following content:

require 'sinatra'

get '/' do
  slim :index
end

post '/start' do
  puts "Starting..."
  redirect '/'
end

post '/stop' do
  puts "Stopping..."
  redirect '/'
end

This basically creates three handlers for paths "/", "/start", "/stop". "/" renders slim html template (we will get there soon), "/start" and "/stop" for now just print a text into STDOUT and redirects you back to "/". Let's create a folder "views" and file "views/index.slim" in it:

doctype html
html
  head
    title Simple Ruby web interface

  body
    form method="post" action="/start"
      input type="submit" value="Start"
    form method="post" action="/stop"
      input type="submit" value="Stop"

This will be rendered into html with two forms with buttons, which will post into /start and /stop on submit. You can run it with just

ruby myapp.rb

This will start a web server on port 4567. Just go to localhost:4567 and press the buttons. Now you can just add actions you need to perform instead of puts "Starting..." and puts "Stopping..." and customize this very basic look of your webapp.

Upvotes: 1

Related Questions