Commit 7f5e49a5 authored by Kirill Smelkov's avatar Kirill Smelkov

Ruby helloweb

Let's show how to do simple helloweb in Ruby. The program generates the
same output as Python version, only the comment about language is
different.

Comes with minimal gem specification, so it could be worked with /
installed via Bundler, together with dependency gems, if needed.

So far we use only stdlib without external gems.

/cc @kazuhiko
parent 686dd5dd
......@@ -10,5 +10,6 @@ The programs are used in SlapOS helloworld_ software release.
The following languages are demonstrated:
- Python
- Ruby
.. _helloworld: https://lab.nexedi.com/nexedi/slapos/tree/master/software/helloworld
source 'https://rubygems.org'
# gem's dependencies are in .gemspec
gemspec
# minimal gem specification for helloweb.rb
Gem::Specification.new do |gem|
gem.name = "helloweb"
gem.version = "0.1"
gem.summary = "Hello Web in Ruby"
gem.bindir = ''
gem.executables = 'helloweb.rb'
# NOTE we can require other gems via
# gem.add_runtime_dependency ...
end
#!/usr/bin/env ruby
# Simple web-server that says "Hello World" for every path
#
# helloweb.rb [--logfile <logfile>] <bind-ip> <bind-port> ...
require 'webrick'
require 'time'
require 'optparse'
require 'ostruct'
def main
args = OpenStruct.new
args.logfile = nil
opt = OptionParser.new
opt.banner = "Usage: helloweb.rb [options] bind_ip bind_port ..."
opt.on('--logfile LOGFILE') { |o| args.logfile = o }
opt.parse!
args.bind_ip = ARGV.delete_at(0)
args.bind_port = ARGV.delete_at(0)
args.argv_extra = ARGV
if args.bind_ip.nil? or args.bind_port.nil?
puts opt
exit 1
end
args.bind_port = Integer(args.bind_port)
log = nil
access_log = nil
if args.logfile
log_file = File.open args.logfile, 'a+'
log_file.sync = true
log = WEBrick::Log.new log_file
access_log = [[log_file, WEBrick::AccessLog::COMBINED_LOG_FORMAT]]
end
httpd = WEBrick::HTTPServer.new :BindAddress => args.bind_ip,
:Port => args.bind_port,
:Logger => log,
:AccessLog => access_log
httpd.mount_proc '/' do |req, resp|
name = args.argv_extra.join(' ')
name = 'world' if name.empty?
resp.body = "Hello #{name} at `#{req.path}` ; #{Time.now.asctime} (ruby)"
end
httpd.start
end
main
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment