require 'rubygems' require 'webrick' require 'markaby' require 'erb' include WEBrick class Action < HTTPServlet::AbstractServlet attr_reader :req, :res, :content_type def do_GET(req, res) @req = req; @res = res @content_type = "text/html" @res.body = get @res['Content-Type'] = @content_type end def do_POST(req, res) @req = req; @res = res @content_type = "text/html" @res.body = post @res['Content-Type'] = @content_type end def get; "GET not defined"; end def post; "POST not defined"; end def render(template, binding=binding) source = IO.read(File.join(File.dirname(__FILE__), 'client', 'templates', "#{template}.rhtml")) puts "Rendering #{source}" ERB.new(source).result(binding) end def site Bloggit::Server.active_site end end class Main < Action def get render('main') end end class Json < Action def get # Get the URI, somehow... #path_parser = Regexp.new("/(\w+)(?:/)()") path_parts = req.path_info.to_s.split('/') path_parts.shift # The first is probably always blank, unless no data type was sent... ? case path_parts.shift when "posts" @count = site.all_posts.length @data = site.all_posts.to_json when "pages" @count = site.all_pages.length @data = site.all_pages.to_json when "settings" @count = 0 @data = "[]" else @count = 0 @data = "[]" end @content_type = 'text/javascript' render('json') end end class Bloggit::Server class << self attr_reader :active_site def run site = Dir.getwd.ends_with?('.blog') ? Bloggit::Site.from_file(Dir.getwd) : nil raise "Not a valid Bloggit site!" if site.nil? @active_site = site s = HTTPServer.new( :Port => 3322, :DocumentRoot => File.join(File.dirname(__FILE__), 'client') ) s.mount( "/main", Main ) s.mount( "/json", Json ) # s.mount_proc("/hello"){|req, res| # res['Content-Type'] = "text/html" # res.body = "hello" # } trap("INT"){ s.shutdown } s.start end end end if __FILE__ == $0 Bloggit::Server.run() end