From 70690604e7ea6fd6b89c256a52d65a308ad0fe77 Mon Sep 17 00:00:00 2001 From: murphy Date: Tue, 17 Oct 2006 09:44:47 +0000 Subject: Moved demos to sample/. --- sample/demo_server.rb | 110 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 110 insertions(+) create mode 100644 sample/demo_server.rb (limited to 'sample/demo_server.rb') diff --git a/sample/demo_server.rb b/sample/demo_server.rb new file mode 100644 index 0000000..ccdff32 --- /dev/null +++ b/sample/demo_server.rb @@ -0,0 +1,110 @@ +# CodeRay dynamic highlighter + +unless ARGV.grep(/-[hv]|--(help|version)/).empty? + puts <<-USAGE +CodeRay Server 0.5 +$Id: demo_server.rb 113 2006-03-15 23:24:37Z murphy $ + +Usage: + 1) Start this and your browser. + 2) Go to http://localhost:2468/? + and you should get the highlighted version. + +Parameters: + -d Debug mode; reload CodeRay engine for every file. + (prepare for MANY "already initialized" and "method redefined" + messages - ingore it.) + + ... More to come. + USAGE + exit +end + +require 'webrick' +require 'pathname' + +class << File + alias dir? directory? +end + +require 'erb' +include ERB::Util +def url_decode s + s.to_s.gsub(/%([0-9a-f]{2})/i) { [$1.hex].pack 'C' } +end + +class String + def to_link name = File.basename(self) + "#{name}" + end +end + +require 'coderay' +class CodeRayServlet < WEBrick::HTTPServlet::AbstractServlet + + STYLE = 'style="font-family: sans-serif; color: navy;"' + BANNER = '

Highlighted by CodeRay

' + + def do_GET req, res + q = req.query_string || '' + args = Hash[*q.scan(/(.*?)=(.*?)(?:&|$)/).flatten].each_value { |v| v.replace url_decode(v) } + path = args.fetch 'path', '.' + + backlinks = '

current path: %s
' % html_escape(path) + + (Pathname.new(path) + '..').cleanpath.to_s.to_link('up') + ' - ' + + '.'.to_link('current') + '

' + + res.body = + if File.dir? path + path = Pathname.new(path).cleanpath.to_s + dirs, files = Dir[File.join(path, '*')].sort.partition { |p| File.dir? p } + + page = "" + page << backlinks + + page << '
' + page << "
Directories
\n" + dirs.map do |p| + "
#{p.to_link}
\n" + end.join << "\n" + page << "
Files
\n" + files.map do |p| + "
#{p.to_link}
\n" + end.join << "\n" + page << "
\n" + page << "#{BANNER}" + + elsif File.exist? path + if $DEBUG + $".delete_if { |f| f =~ /coderay/ } + require 'coderay' + end + div = CodeRay.scan_file(path).html :tab_width => 8, :wrap => :div, :hint => :info + div.replace <<-DIV +
+ #{backlinks} +#{div} +
+ #{BANNER} + DIV + div.page + end + + res['Content-Type'] = 'text/html' + end +end + +# This port is taken by "qip_msgd" - I don't know that. Do you? +module CodeRay + PORT = 0xC0DE / 20 +end + +server = WEBrick::HTTPServer.new :Port => CodeRay::PORT + +server.mount '/', CodeRayServlet + +server.mount_proc '/version' do |req, res| + res.body = 'CodeRay::Version = ' + CodeRay::Version + res['Content-Type'] = "text/plain" +end + +trap("INT") { server.shutdown } +server.start -- cgit v1.2.1