huge: changed to roda

now works same as before, but much more extensible.  Internally, a
routing tree is used.
This commit is contained in:
Pranshu Sharma 2025-06-01 00:43:19 +10:00
parent e005cc96e9
commit 094189e2cb
3 changed files with 87 additions and 27 deletions

101
app.rb
View file

@ -1,5 +1,5 @@
require 'sinatra'
require 'roda'
require 'erb'
require 'nokogiri'
require 'redcarpet'
@ -16,8 +16,7 @@ class Config
@approved_regex = Regexp.union(approved_files)
toml = Tomlib.load(File.read "config.toml")
@layout = toml["layout"] || "layout"
@layout = @layout.to_sym
@layout = toml["layout"] || "layout.erb"
# @layout = :layout
end
@ -26,6 +25,7 @@ end
$config = Config.new();
class Sidebar
attr_reader :tree
FileNode = Struct.new(:type, :path, :name)
DirNode = Struct.new(:type, :path, :name, :files)
@ -45,6 +45,7 @@ class Sidebar
end
def html
return @html if defined?(@html)
builder = Nokogiri::HTML::Builder.new do |doc|
def deal_with_dir (doc, dir, path)
doc.li {
@ -67,7 +68,7 @@ class Sidebar
deal_with_dir doc, @tree, @tree.path
}
end
builder.to_html().split(/\n/)[1..-1].join
@html = builder.to_html().split(/\n/)[1..-1].join
end
private
@ -105,29 +106,79 @@ end
$sidebar = Sidebar.new
class Perc < Sinatra::Application
set :views, "."
set :markdown, :layout_engine => :erb
# @sidebar = Sidebar.new
class App < Roda
route do |r|
r.root do
pview "main.erb"
end
process_dir r, $sidebar.tree, "."
end
# Now the saga begins,we transform file_tree into a routing tree
def process_dir (r, dir, cdir)
p = Proc.new do
dir.files.each do |f|
dd = File.join(cdir, f.path)
if f.type == :dir
# f is dir
process_dir r, f, dd
else
# f is a file
r.get f.path do
pview dd
end
end
end
"Whatup"
end
if dir.path == "."
p.call
else
r.on dir.path do
p.call
end
end
end
def tree
$sidebar.html
end
get "/" do
erb :main, layout: $config.layout
end
get "/*.*" do |path, ext|
if ext == "md"
md = markdown File.read(path + ".md"), layout: $config.layout
else
erb path.to_sym, layout: $config.layout
end
end
helpers do
def tree
$sidebar.html
end
def pview(file)
layout = $config.layout
tp = ERB.new(File.read(file))
body = tp.result(binding)
ERB.new(File.read(layout)).result(binding)
end
end
# class Perc < Sinatra::Application
# set :views, "."
# set :markdown, :layout_engine => :erb
# # @sidebar = Sidebar.new
# get "/" do
# erb :main, layout: $config.layout
# end
# get "/*.*" do |path, ext|
# if ext == "md"
# md = markdown File.read(path + ".md"), layout: $config.layout
# else
# erb path.to_sym, layout: $config.layout
# end
# end
# helpers do
# def tree
# $sidebar.html
# end
# end
# end