Skip to content
Permalink
Browse files

Add simple ruby webserver for templating

  • Loading branch information...
Jakob Holderbaum
Jakob Holderbaum committed Oct 1, 2018
1 parent 22cf462 commit 0b343cb205ac14656f62ea5a4b3147c9e49b8ab6
Showing with 112 additions and 0 deletions.
  1. +2 −0 .gitignore
  2. +4 −0 Gemfile
  3. +45 −0 Gemfile.lock
  4. +4 −0 config.ru
  5. +57 −0 lib/server.rb
@@ -0,0 +1,2 @@
vendor/*
.bundle/
@@ -0,0 +1,4 @@
source 'https://rubygems.org'

gem 'sinatra'
gem 'sinatra-contrib'
@@ -0,0 +1,45 @@
GEM
remote: https://rubygems.org/
specs:
activesupport (5.2.1)
concurrent-ruby (~> 1.0, >= 1.0.2)
i18n (>= 0.7, < 2)
minitest (~> 5.1)
tzinfo (~> 1.1)
backports (3.11.4)
concurrent-ruby (1.0.5)
i18n (1.1.0)
concurrent-ruby (~> 1.0)
minitest (5.11.3)
multi_json (1.13.1)
mustermann (1.0.3)
rack (2.0.5)
rack-protection (2.0.4)
rack
sinatra (2.0.4)
mustermann (~> 1.0)
rack (~> 2.0)
rack-protection (= 2.0.4)
tilt (~> 2.0)
sinatra-contrib (2.0.4)
activesupport (>= 4.0.0)
backports (>= 2.8.2)
multi_json
mustermann (~> 1.0)
rack-protection (= 2.0.4)
sinatra (= 2.0.4)
tilt (>= 1.3, < 3)
thread_safe (0.3.6)
tilt (2.0.8)
tzinfo (1.2.5)
thread_safe (~> 0.1)

PLATFORMS
ruby

DEPENDENCIES
sinatra
sinatra-contrib

BUNDLED WITH
1.16.1
@@ -0,0 +1,4 @@
$LOAD_PATH.unshift(File.expand_path('lib', __dir__))
require 'server'

run Server
@@ -0,0 +1,57 @@
require 'sinatra/base'
require 'sinatra/reloader'

class Result
attr_reader :content, :type

def initialize(content, type)
@content = content
@type = type
end
end

class ServerError < RuntimeError
attr_reader :type, :text

def initialize(type, text)
@type = type
@text = text
end
end

class Server < Sinatra::Application
def resolve_path(file)
p :resolve_path => file
return file if File.file? file
return resolve_path(file + '.erb') if File.file? file + '.erb'
return resolve_path(File.join(file, 'index.html')) if File.directory? file
raise ServerError.new(404, "File not found: #{file}")
end

def resolve_type(filename)
case File.extname(filename.gsub(/\.erb$/, ''))
when '.css'
'text/css'
when '.svg'
'image/svg+xml'
when '.png'
'image/png'
else
'text/html'
end
end

def render(file)
Result.new(File.read(file), resolve_type(file))
end

get '/*' do
begin
result = render(resolve_path(params[:splat].first))
content_type result.type
result.content
rescue ServerError => e
[e.type, e.text]
end
end
end

0 comments on commit 0b343cb

Please sign in to comment.
You can’t perform that action at this time.