Skip to content

Commit

Permalink
Add simple ruby webserver for templating
Browse files Browse the repository at this point in the history
  • Loading branch information
Jakob Holderbaum committed Oct 1, 2018
1 parent 22cf462 commit 0b343cb
Show file tree
Hide file tree
Showing 5 changed files with 112 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
vendor/*
.bundle/
4 changes: 4 additions & 0 deletions Gemfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
source 'https://rubygems.org'

gem 'sinatra'
gem 'sinatra-contrib'
45 changes: 45 additions & 0 deletions Gemfile.lock
Original file line number Diff line number Diff line change
@@ -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
4 changes: 4 additions & 0 deletions config.ru
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
$LOAD_PATH.unshift(File.expand_path('lib', __dir__))
require 'server'

run Server
57 changes: 57 additions & 0 deletions lib/server.rb
Original file line number Diff line number Diff line change
@@ -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.