require 'roda' require 'erb' require 'nokogiri' require 'redcarpet' require 'tomlib' $root = "/home/pranshu/Documents/proj/perc/test" Dir.chdir $root; class Config attr_reader :approved_regex, :layout def initialize approved_files = [/\.md$/, /\.erb$/] @approved_regex = Regexp.union(approved_files) toml = Tomlib.load(File.read "config.toml") @layout = toml["layout"] || "layout.erb" # @layout = :layout end end $config = Config.new(); class Sidebar attr_reader :tree FileNode = Struct.new(:type, :path, :name) DirNode = Struct.new(:type, :path, :name, :files) def initialize @tree = process_dir "." end def show(n=@tree, indent="") if n.type == :dir print indent, n.path, "\n" n.files.each do |r| show r, " " + indent end else print indent, n.path, "\n" end end def html return @html if defined?(@html) builder = Nokogiri::HTML::Builder.new do |doc| def deal_with_dir (doc, dir, path) doc.li { doc.text dir.path doc.ul { dir.files.each do |f| fpath = File.join(path, f.path) if f.type == :dir deal_with_dir doc, f, fpath else doc.a(:href => "/#{fpath}") { doc.li { doc.text f.name } } end end } } end doc.div { deal_with_dir doc, @tree, @tree.path } end @html = builder.to_html().split(/\n/)[1..-1].join end private def getname(file) File.basename(file, File.extname(file)) end def dir_files() # Remove "." and ".." from file list Dir.entries(".").filter {|f| f !~ /^\./ }.filter do |f| if File.file? f f =~ $config.approved_regex else true end end end def process_dir(dir) DirNode.new(:dir, dir, getname(dir), Dir.chdir(dir) do dir_files.map do |f| if File.file? f FileNode.new(:file, f, getname(f)) else process_dir f end end end) end end $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 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