Alpha Chen 1 year ago
parent 019a31f483
commit 0cf17ab5ac
Signed by: alpha
SSH Key Fingerprint: SHA256:3fOT8fiYQG/aK9ntivV3Bqtg8AYQ7q4nV6ZgihOA20g

@ -5,9 +5,14 @@ if dev
logger = Logger.new($stdout) logger = Logger.new($stdout)
end end
require "rack/unreloader" require "rack/unreloader"
Unreloader = Rack::Unreloader.new(subclasses: %w[Roda Sequel::Model], logger: logger, reload: dev, autoload: dev){App} Unreloader = Rack::Unreloader.new(
require_relative "lib/models" subclasses: %w[Roda Sequel::Model Phlex::HTML],
Unreloader.require("lib/app.rb"){'App'} logger: logger,
run(dev ? Unreloader : App.freeze.app) reload: dev,
autoload: dev,
) { RankKing::App }
# require_relative("lib/models")
Unreloader.require("lib/views.rb")
Unreloader.require("lib/app.rb") { "RankKing::App" }
run(dev ? Unreloader : RankKing::App.freeze.app)

@ -1,159 +1,121 @@
# frozen_string_literal: true # frozen_string_literal: true
require_relative "models" require_relative "models"
require_relative "views"
require "roda" require "roda"
class App < Roda module RankKing
opts[:check_dynamic_arity] = false class App < Roda
opts[:check_arity] = :warn opts[:check_dynamic_arity] = false
opts[:check_arity] = :warn
plugin :default_headers,
"Content-Type" => "text/html", plugin :default_headers,
# "Strict-Transport-Security" => "max-age=16070400;", # Uncomment if only allowing https:// access "Content-Type" => "text/html",
"X-Frame-Options" => "deny", # "Strict-Transport-Security" => "max-age=16070400;", # Uncomment if only allowing https:// access
"X-Content-Type-Options" => "nosniff", "X-Frame-Options" => "deny",
"X-XSS-Protection" => "1; mode=block" "X-Content-Type-Options" => "nosniff",
"X-XSS-Protection" => "1; mode=block"
plugin :content_security_policy do |csp|
csp.default_src :none plugin :content_security_policy do |csp|
# csp.style_src :self, "https://cdn.jsdelivr.net" csp.default_src :none
csp.form_action :self # csp.style_src :self, "https://cdn.jsdelivr.net"
csp.script_src :self csp.form_action :self
csp.connect_src :self csp.script_src :self
csp.base_uri :none csp.connect_src :self
csp.frame_ancestors :none csp.base_uri :none
end csp.frame_ancestors :none
# css_opts = {cache: false, style: :compressed}
# :nocov:
# if ENV["RACK_ENV"] == 'development'
# css_opts.merge!(source_map_embed: true, source_map_contents: true, source_map_file: ".")
# end
plugin :render_coverage if defined?(SimpleCov)
# :nocov:
plugin :route_csrf
plugin :flash
# plugin :assets, css: "app.scss", css_opts: css_opts, timestamp_paths: true
# plugin :render, escape: true, layout: "./layout", :template_opts=>{chain_appends: !defined?(SimpleCov), freeze: true, skip_compiled_encoding_detection: true}
plugin :render, engine: :phlex
# plugin :public
plugin :Integer_matcher_max
plugin :typecast_params_sized_integers, sizes: [64], default_size: 64
plugin :hash_branch_view_subdir
logger = if ENV["RACK_ENV"] == "test"
Class.new{def write(_) end}.new
else
$stderr
end
plugin :common_logger, logger
plugin :not_found do
@page_title = "File Not Found"
view(content: "")
end
if ENV["RACK_ENV"] == "development"
plugin :exception_page
class RodaRequest
def assets
exception_page_assets
super
end
end end
else
def self.freeze
Sequel::Model.freeze_descendents
DB.freeze
super
end
end
plugin :error_handler do |e| # css_opts = {cache: false, style: :compressed}
case e # :nocov:
when Roda::RodaPlugins::RouteCsrf::InvalidToken # if ENV["RACK_ENV"] == 'development'
@page_title = "Invalid Security Token" # css_opts.merge!(source_map_embed: true, source_map_contents: true, source_map_file: ".")
response.status = 400 # end
view(content: "<p>An invalid security token was submitted with this request, and this request could not be processed.</p>") # plugin :render_coverage if defined?(SimpleCov)
# :nocov:
plugin :route_csrf
plugin :flash
# plugin :assets, css: "app.scss", css_opts: css_opts, timestamp_paths: true
# plugin :render, escape: true, layout: "./layout", :template_opts=>{chain_appends: !defined?(SimpleCov), freeze: true, skip_compiled_encoding_detection: true}
# plugin :public
plugin :Integer_matcher_max
plugin :typecast_params_sized_integers, sizes: [64], default_size: 64
# plugin :hash_branch_view_subdir
plugin :custom_block_results
logger = if ENV["RACK_ENV"] == "test"
Class.new{def write(_) end}.new
else else
$stderr.print "#{e.class}: #{e.message}\n" $stderr
$stderr.puts e.backtrace
next exception_page(e, assets: true) if ENV["RACK_ENV"] == "development"
@page_title = "Internal Server Error"
view(content: "")
end end
end plugin :common_logger, logger
plugin :sessions, plugin :not_found do
key: "_App.session", @page_title = "File Not Found"
#cookie_options: {secure: ENV['RACK_ENV'] != 'test'}, # Uncomment if only allowing https:// access view(content: "")
secret: ENV.send((ENV["RACK_ENV"] == "development" ? :[] : :delete), "APP_SESSION_SECRET") end
# if Unreloader.autoload?
# plugin :autoload_hash_branches
# autoload_hash_branch_dir("./routes")
# end
# Unreloader.autoload("routes", delete_hook: proc{|f| hash_branch(File.basename(f).delete_suffix(".rb"))}){}
route do |r|
# r.public
# r.assets
check_csrf!
r.root do if ENV["RACK_ENV"] == "development"
@page_title = "Foo" plugin :exception_page
class RodaRequest
def assets
exception_page_assets
super
end
end
else
def self.freeze
Sequel::Model.freeze_descendents
DB.freeze
super
end
end
# render("hello", locals: {name: "Alice"}) plugin :error_handler do |e|
view("hello", locals: {name: "Bob"}) case e
when Roda::RodaPlugins::RouteCsrf::InvalidToken
@page_title = "Invalid Security Token"
response.status = 400
view(content: "<p>An invalid security token was submitted with this request, and this request could not be processed.</p>")
else
$stderr.print "#{e.class}: #{e.message}\n"
$stderr.puts e.backtrace
next exception_page(e, assets: true) if ENV["RACK_ENV"] == "development"
# @page_title = "Internal Server Error"
# view(content: "")
end
end end
end
end
require "tilt/template" plugin :sessions,
require "phlex" key: "_App.session",
#cookie_options: {secure: ENV['RACK_ENV'] != 'test'}, # Uncomment if only allowing https:// access
secret: ENV.send((ENV["RACK_ENV"] == "development" ? :[] : :delete), "APP_SESSION_SECRET")
module Tilt # if Unreloader.autoload?
class PhlexTemplate < Template # plugin :autoload_hash_branches
def prepare # autoload_hash_branch_dir("./routes")
end # end
# Unreloader.autoload("routes", delete_hook: proc{|f| hash_branch(File.basename(f).delete_suffix(".rb"))}){}
# I have no idea how this works - it's just copied pretty much blindly from here: # def render(view, layout=Views::Layout.new)
# # component.call
# https://github.com/phlex-ruby/phlex-rails/blob/main/lib/phlex/rails/layout.rb#L18 # end
def evaluate(scope, locals, &block)
klass = Class.new(Phlex::HTML)
klass.class_eval(data, __FILE__, __LINE__)
component = klass.new route do |r|
# r.public
# r.assets
check_csrf!
scope.instance_variables r.root do
.reject { _2.start_with?("@_") } Views::Layout.new(Views::Hello.new(name: "Bob")).call
.each do |k|
component.instance_variable_set(k, scope.instance_variable_get(k))
end
locals.each do |k,v|
component.instance_variable_set("@#{k}", v)
end end
component.call do |yielded| r.on "pools" do
output = yield r.is "new" do
component.unsafe_raw(output) Views::Layout.new(Views::NewPool.new).call
end
end end
end end
# Not sure if this is better...?
# def precompiled_preamble(*) = "klass = Class.new(Phlex::HTML) do"
# def precompiled_template(*) = data
# def precompiled_postamble(locals) = <<~RUBY
# end
# component = klass.new(**locals)
# component.call do |yielded|
# output = yield
# component.unsafe_raw(output)
# end
# RUBY
end end
end end
Tilt.register(Tilt::PhlexTemplate, "phlex")

@ -16,7 +16,7 @@ unless defined?(Unreloader)
Unreloader = Rack::Unreloader.new(reload: false, autoload: !ENV["NO_AUTOLOAD"]) Unreloader = Rack::Unreloader.new(reload: false, autoload: !ENV["NO_AUTOLOAD"])
end end
Unreloader.autoload("models"){|f| Sequel::Model.send(:camelize, File.basename(f).sub(/\.rb\z/, ''))} # Unreloader.autoload("models"){|f| Sequel::Model.send(:camelize, File.basename(f).sub(/\.rb\z/, ''))}
if ENV["RACK_ENV"] == "development" || ENV["RACK_ENV"] == "test" if ENV["RACK_ENV"] == "development" || ENV["RACK_ENV"] == "test"
require "logger" require "logger"

@ -0,0 +1,43 @@
require "phlex"
module RankKing
module Views
class Layout < Phlex::HTML
def initialize(view)
@view = view
end
def template
doctype
html(lang: "en") do
head do
meta(charset: "utf-8")
meta(name: "viewport", content: "width=device-width, initial-scale=1")
title { "Rank King" }
end
body do
header do
h1 { "Rank King" }
end
nav
main do
render @view
end
footer
end
end
end
end
class NewPool < Phlex::HTML
def template
plain "ohai"
end
end
end
end

@ -1,3 +0,0 @@
def template
h1 { "👋 Hello #@name!" }
end

@ -1,5 +0,0 @@
def template
article do
yield
end
end
Loading…
Cancel
Save