Example for a Minimal Thin App
Here you can see an example for a minimal app that can be hooked up using the Thin ruby server (or using the new Rails 3 routing system).
It was tested with Ruby 1.9.2-head and (important for me) also handles UTF-8 characters like ÄÖÜ umlauts without problems.
Sometimes a clean code example is just better to understand than a whole tutorial.
require 'cgi'
# This class is an example for a minimal app# That can be used with the thin web server.class MyApp
STATUS_OK = 200
STATUS_NOT_MODIFIED = 304
STATUS_NOT_FOUND = 404
STATUS_BAD_REQUEST = 400
attr_accessor :content
attr_accessor :status
attr_reader :query
# Prepares the resonse for thin server def send_response(response_status = STATUS_OK)
@status = response_status
headers = { 'Content-Type' => 'text/html; charset=utf-8', # NOTE: Use bytesize instead of size/length to get # the correct size for utf-8 chars, e.g. umlauts. 'Content-Length' => content.bytesize.to_s, 'Server' => 'My App Name' }
# NOTE: If you collect the content as a String # you have to put it into an Array iteral so Thin # can iterate over it in Ruby 1.9 response = [status, headers, [content]]
end
# Parses the query variables into a Hash. # Keys are always Strings. # Doublettes are joined into one String. def parse_query(query_string) begin
uri_params = CGI.parse(query_string)
@query = {}
uri_params.each {|k, v| @query[k.to_sym] = v.join("") }
rescue @query = {} end end
# This method is invoked by thin at every request. def call(env)
# parse query string parse_query env['QUERY_STRING'] # reset content @content = ''
@content << '######## ECHO START #########' @content << @query.to_s @content << '######## ECHO END #########'
send_response
end
end
app = Rack::Builder.new do use Rack::CommonLogger use Rack::ShowExceptions
map "/" do use Rack::Lint run MyApp.new end end
run app
# start with# thin start -R my_rack_app.ru
Have a nice weekend!










No Comments, Comment or Ping
Reply to “Example for a Minimal Thin App”