1. Computing

Making Forms and Views

By

The next step is to make some forms. We know how we want to submit the requests and to which URLs, we just need to write up for forms for this. For the most part, these forms will be single text fields in this application, but there are some instances where a number of options will be supplied. It's easy to get carried away here, providing dropdowns and check boxes for every single option the program or gem takes. The line has to be drawn somewhere though, and it's best to optimize the user interface for the most common use cases. You can also provide a second "advanced" form with all the options you want on it, for advanced users who know what they all do.

To cut down on redundancy, both of the form and result pages use the same view. The form is always displayed at the top, and if there was data submitted to the form, it's displayed in its fields. If there are any results to display, they're displayed below the form.

#!/usr/bin/env ruby
require 'rubygems'
require 'sinatra'
require 'haml'

get '/' do
  haml :index
end

# whois
get '/whois' do
  haml :whois
end

post '/whois' do
  @host = params[:host]

  haml :whois
end

# traceroute
get '/traceroute' do
  haml :traceroute
end

post '/traceroute' do
  @host = params[:host]

  haml :traceroute
end

__END__
@@ layout
%html
  %head
    %title Network Tools
  %body
    #header
      %h1 Network Tools
    #content
      =yield
  %footer
    %a(href='/') Back to index

@@ index
%p
  Welcome to Network Tools. Below is a list
  of the tools available.
%ul
  %li
    %h3
      %a(href='/whois') Whois
  %li
    %h3
      %a(href='/traceroute') Traceroute

@@ whois
%h3 Whois
%form(action='/whois' method='POST')
  %input(type='text' name='host' value=@host)
  %input(type='submit')
- if defined?(@results)
  %pre= @results

@@ traceroute
%h3 Traceroute
%form(action='/traceroute' method='POST')
  %input(type='text' name='host' value=@host)
  %input(type='submit')
- if defined?(@results)
  %pre= @results
  1. About.com
  2. Computing
  3. Ruby
  4. Tutorials
  5. Sinatra
  6. Making Forms and Views

©2014 About.com. All rights reserved.