Ruby/CGI/HTML

Материал из Wiki.crossplatform.ru

(Различия между версиями)
Перейти к: навигация, поиск
м (1 версия)
 

Текущая версия на 17:57, 13 сентября 2010

Содержание

CGI.escape and CGI.unescape.

require "cgi" 
puts CGI.escape("Nicholas Payton/Trumpet & Flugel Horn")



CGI.escapeElement

require "cgi" 
puts CGI.escapeElement("<hr><a href="/mp3">Click Here</a><br>","A")



CGI.escapeHTML

require "cgi" 
puts CGI.escapeHTML("a < 100 && b > 200")



CGI for creating a web page

#!/ruby/bin/ruby
require "cgi"
cgi=CGI.new("html3")
cgi.out{
     cgi.html{
            cgi.head{cgi.title{"My First Page"}}
            cgi.body{cgi.h1{"Hello, Welcome to the World of Ruby"}}
            }
     }



CGI.unescapeHTML

require "cgi" 
puts CGI.unescapeHTML("a &lt; 100 &amp;&amp; b &gt; 200")



Create a hash of HTTP response headers

#!/usr/bin/ruby
require "cgi"
cgi = CGI.new("html3")
header = { "status"      => "OK",
           "cookie"      => [cookie],
           "Refresh"     => 2,
           "Recipe Name" => "Setting HTTP Response Headers",
           "server"      => ENV["SERVER_SOFTWARE"]  }
cgi.out(header) do
  cgi.html("PRETTY" => "  ") do
    cgi.head { cgi.title { "Setting HTTP Response Headers" } } +
    cgi.body do
      cgi.p("Your headers:") +
      cgi.pre{ cgi.header(header) } +
      cgi.pre do
        "#: #{hits}\n"+
        "Last connected: #{last}"
      end
    end
 end
end



Generating HTML

require "cgi" 
cgi = CGI.new("html3") # add HTML generation methods 
cgi.out { 
    cgi.html { 
        cgi.head { "\n"+cgi.title{"This Is a Test"} } + 
        cgi.body { "\n"+ 
            cgi.form {"\n"+ 
                cgi.hr + 
                cgi.h1 { "A Form: " } + "\n"+ 
                cgi.textarea("get_text") +"\n"+ 
                cgi.br + 
                cgi.submit 
            } 
        } 
    } 
}



nested cgi.tag to create HTML document

#!/usr/bin/ruby
require "cgi"
cgi = CGI.new("html3")
processes = "ps aux".collect { |proc| proc.split(/\s+/, 11) }
title = %{Processes running on #{ENV["SERVER_NAME"] || %x{hostname}.strip}}
cgi.out do
  cgi.html do
    cgi.head { cgi.title { title } } + cgi.body do
      cgi.table do
        (processes.collect do |fields|
          cgi.tr { fields.collect { |field| cgi.td { field } }.join " " }
        end).join "\n"
      end
    end
  end
end
exit 0



Output a string to web

#!/usr/bin/ruby
# closed_cgi.rb
require "cgi"
c = CGI.new("html4")
c.out do
  c.html do
    c.h1 { "Sorry, the Web is closed." }
  end
end
# Content-Type: text/html
# Content-Length: 137
# <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
#   "http://www.w3.org/TR/html4/strict.dtd">
# <HTML><H1>Sorry, the Web is closed.</H1></HTML>