简体   繁体   中英

How to create a server in Ruby (like rails server or gem server)?

A lot of ruby frameworks implement a server to serve up dynamic html documents. I am looking to create my own server so that I can serve up my own local rdoc documentation. How does one create a server in ruby like rails server or gem server ? Can somebody give me a start or point me to some documentation on how to do this? Thanks

Sinatra is a good way to go, especially if you are generating the HTML on the fly. Here's a quick example as a command line tool:

example.rb:

options = {}

parser = OptionParser.new do |opts|
  opts.banner = "Usage: example [command] [options]"

  opts.on("-a", "--address HOST") { |arg| options[:bind] = arg }
  opts.on("-p", "--port PORT")    { |arg| options[:port] = arg }
end

parser.parse(ARGV)

case command = ARGV.first.to_sym
when :serve
  require "server"
  Example::Server.run! options
else
  raise "Unknown command: #{command}"
end

server.rb:

require "rubygems"
require "sinatra/base"

module Example
  class Server < Sinatra::Base
    get "/" do
      "Generate some HTML here."
    end
  end
end

Personally I'd use rdoc to create my HTML docs based on the comments in my code, then use a standard HTML server like nginx or apache to handle the serving part. Trying to reinvent those httpd-wheels will require a lot of coding on your part.

Otherwise, Sinatra, as mentioned by Todd, and/or Rack will be good starting points to build on without completely rolling your own server. In particular, Rack was written to make it easier to build web services, so becoming familiar with what it offers will save you a lot of work.

http://rack.rubyforge.org/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM