Skip to content

Commit 406f561

Browse files
author
Olivier Bonnaure
committed
feat: ContentFor & YieldContent
1 parent 12e1ddf commit 406f561

File tree

5 files changed

+99
-40
lines changed

5 files changed

+99
-40
lines changed

.lua/arango_model.lua

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ function ArangoModel.new(data)
66
self.filters = {}
77
self.bindvars = {}
88
self.sort = "doc._id ASC"
9-
self.data = data
9+
self.data = data or {}
1010
self.var_index = 0
1111
self.global_callbacks = {
1212
before_create = { "run_before_create_callback" },
@@ -198,7 +198,7 @@ function ArangoModel:validates_each(data)
198198
local default_error = I18n:t("models.errors.presence")
199199
if v == true then v = { message = default_error } end
200200
if v.message == nil then v.message = default_error end
201-
if value == nil then
201+
if value == nil or value == "" then
202202
self.errors = table.append(self.errors, {{ field = field, message = v.message }})
203203
end
204204
end
@@ -397,7 +397,7 @@ end
397397
-- collection
398398

399399
function ArangoModel:create(data)
400-
assert(self.data == nil, "create not allowed here")
400+
assert(self.data._id == nil, "create not allowed here")
401401
local callbacks = table.append(self.global_callbacks.before_create, self.callbacks.before_create)
402402
for _, methodName in pairs(callbacks) do data = self[methodName](data) end
403403

@@ -407,6 +407,8 @@ function ArangoModel:create(data)
407407
self.data = Adb.primary:CreateDocument(self.COLLECTION, data, "returnNew=true")["new"]
408408
callbacks = table.append(self.global_callbacks.after_create, self.callbacks.after_create)
409409
for _, methodName in pairs(callbacks) do self[methodName](self) end
410+
else
411+
self.data = data
410412
end
411413
return self
412414
end

.lua/luaonbeans.lua

Lines changed: 69 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ PGRest = {}
66
Rest = {}
77
Surreal = {}
88

9+
Blocks = {}
10+
911
function LoadViewsRecursively(path)
1012
local dir = unix.opendir(path)
1113
assert(dir ~= nil, "Error while opening path " .. path)
@@ -101,6 +103,22 @@ function Partial(partial, bindVars)
101103
return Views["app/views/partials/" .. partial .. ".html.etlua"](bindVars)
102104
end
103105

106+
---Helper method ContentFor
107+
---@param tag string name of the content
108+
---@param fn function the function to be executed
109+
---@return nil
110+
function ContentFor(tag, block)
111+
Blocks[tag] = Blocks[tag] or {}
112+
table.insert(Blocks[tag], block())
113+
end
114+
115+
---Helper method YieldContent
116+
---@param tag string name of the content
117+
---@return string content
118+
function YieldContent(tag)
119+
return table.concat(Blocks[tag], "\n")
120+
end
121+
104122
local function assignRoute(method, name, options, value)
105123
local path = string.split(name, "/")
106124
Routes[method] = Routes[method] or {}
@@ -351,12 +369,13 @@ end
351369

352370
function GetBodyParams()
353371
local body_Params = {}
354-
for i, data in pairs(Params) do
355-
if type(data) == "table" then
372+
for _, data in pairs(Params) do
373+
if type(data) == "table" and #data > 1 then
356374
body_Params[data[1]] = data[2]
357375
end
358376
end
359377

378+
Params = table.merge(Params, body_Params)
360379
return body_Params
361380
end
362381

@@ -404,14 +423,14 @@ function InitDB(db_config)
404423
sqlite:exec([[PRAGMA journal_mode=WAL]])
405424
sqlite:exec([[PRAGMA synchronous=NORMAL]])
406425
sqlite:exec([[
407-
CREATE TABLE IF NOT EXISTS "migrations"
408-
(
409-
id integer PRIMARY KEY,
410-
filename VARCHAR
411-
);
412-
413-
CREATE UNIQUE INDEX idx_migrations_filename ON migrations (filename);
414-
]])
426+
CREATE TABLE IF NOT EXISTS "migrations"
427+
(
428+
id integer PRIMARY KEY,
429+
filename VARCHAR
430+
);
431+
432+
CREATE UNIQUE INDEX idx_migrations_filename ON migrations (filename);
433+
]])
415434
elseif config.engine == "surrealdb" then
416435
local _Surreal = require("db.surrealdb")
417436
Surreal[config.name] = _Surreal.new(config)
@@ -459,7 +478,10 @@ function LoadPublicAssetsRecursively(path)
459478
end
460479

461480
RunCommand = function(command)
462-
command = string.split(command)
481+
if type(command) == "string" then
482+
command = string.split(command)
483+
end
484+
463485
local prog = assert(Unix.commandv(command[1]))
464486

465487
local output = ""
@@ -530,3 +552,39 @@ function RefreshPageForDevMode()
530552
end
531553
end
532554

555+
-- View form errors
556+
local function ExtractModelError(inputTable, allowedField)
557+
local messages = {}
558+
559+
-- Collect messages for the allowed field
560+
for _, v in ipairs(inputTable) do
561+
if v.field == allowedField then
562+
table.insert(messages, v.message)
563+
end
564+
end
565+
566+
return messages
567+
end
568+
569+
local function DisplayErrorFor(model_errors, field, style)
570+
style = style or "color:red"
571+
local errors = ExtractModelError(model_errors, field)
572+
if #errors > 0 then
573+
for _, error in pairs(errors) do
574+
return [[<div style="%s">%s</div>]] % { style, error }
575+
end
576+
else
577+
return ""
578+
end
579+
end
580+
581+
function TextField(name, field, model, options)
582+
options = options or {}
583+
local value = options.novalue == true and "" or model.data[field]
584+
local required = options.required == true and "required" or ""
585+
586+
return [[
587+
<label class="font-bold" for="firstname">%s</label>
588+
<input type="text" name="%s" value="%s" %s />%s
589+
]] % { name, field, value or "", required, DisplayErrorFor(model.errors, field, options.error_style) }
590+
end

.lua/utilities/csrf.lua

Lines changed: 12 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,21 @@
1-
CSRFToken = EncodeBase64(GetRandomBytes(64))
2-
31
CheckCSRFToken = function()
42
if GetMethod() == "POST" then
53
local crypted_token = EncodeBase64(GetCryptoHash("SHA256", GetBodyParams()["authenticity_token"], ENV['SECRET_KEY']))
6-
print(GetBodyParams()["authenticity_token"],crypted_token, GetCookie("_authenticity_token"))
7-
assert(crypted_token == GetCookie("_authenticity_token"))
4+
assert(crypted_token == GetCookie("_authenticity_token"), "Bad authenticity_token")
85
end
96
end
107

118
AuthenticityTokenTag = function()
12-
if GetCookie("_authenticity_token") == nil then
13-
CSRFToken = EncodeBase64(GetRandomBytes(64))
14-
print(CSRFToken, EncodeBase64(GetCryptoHash("SHA256", CSRFToken, ENV['SECRET_KEY'])))
15-
SetCookie(
16-
"_authenticity_token",
17-
EncodeBase64(GetCryptoHash("SHA256", CSRFToken, ENV['SECRET_KEY'])),
18-
{
19-
HttpOnly = true,
20-
MaxAge = 60 * 30,
21-
SameSite = "Strict"
22-
} -- available for 30 minutes
23-
)
24-
end
9+
local CSRFToken = EncodeBase64(GetRandomBytes(64))
10+
SetCookie(
11+
"_authenticity_token",
12+
EncodeBase64(GetCryptoHash("SHA256", CSRFToken, ENV['SECRET_KEY'])),
13+
{
14+
HttpOnly = true,
15+
MaxAge = 60 * 30,
16+
SameSite = "Strict",
17+
Path="/"
18+
} -- available for 30 minutes
19+
)
2520
return '<input type="hidden" name="authenticity_token" value="' .. CSRFToken .. '" />'
2621
end

app/controllers/welcome_controller.lua

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,8 @@ local app = {
2121

2222
-- Add a page (default A4 size)
2323
pdf:addPage()
24-
--pdf:addCustomFont("fonts/Helvetica.ttf", "helvetica", "normal")
25-
--pdf:addCustomFont("fonts/Helvetica-Bold.ttf", "helvetica", "bold")
24+
pdf:addCustomFont("fonts/Helvetica.ttf", "helvetica", "normal")
25+
pdf:addCustomFont("fonts/Helvetica-Bold.ttf", "helvetica", "bold")
2626
pdf:addCustomFont("fonts/TitilliumWeb-Regular.ttf", "titillium", "normal")
2727
pdf:addCustomFont("fonts/TitilliumWeb-Bold.ttf", "titillium", "bold")
2828

@@ -31,6 +31,8 @@ local app = {
3131

3232
pdf:moveY(10)
3333

34+
--pdf:useFont("helveltica")
35+
3436
-- Add some text
3537
pdf:addParagraph([[
3638
Morbi ultrices pharetra risus sed pellentesque. Integer id semper erat. Duis lobortis mollis erat, id commodo orci lobortis ut. Sed laoreet libero sed lorem sagittis, et lacinia arcu efficitur. Curabitur eu scelerisque elit. Aenean enim turpis, congue nec ipsum non, dapibus laoreet ex. Cras viverra congue tortor vitae rutrum.

beans.lua

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ CreateModel = function(model_name)
9999
print("✅ specs/models/" .. words.singular .. "_spec.lua created")
100100
end
101101

102-
if arg[1] == "create" then
102+
if arg[1] == "create" or arg[1] == "g" then
103103
if arg[2] == "migration" then
104104
CreateMigration(arg[3])
105105
end
@@ -153,7 +153,7 @@ SetupArangoDB = function(env)
153153
end
154154

155155
if arg[1] == "db:setup" then
156-
if DBConfig["engine"] == "arangodb" then
156+
if DBConfig[BeansEnv][1]["engine"] == "arangodb" then
157157
SetupArangoDB(BeansEnv)
158158
end
159159
end
@@ -205,16 +205,18 @@ Sqlite_DBMigrate = function()
205205
end
206206

207207
if arg[1] == "db:migrate" then
208-
if DBConfig["engine"] == "arangodb" then
208+
if DBConfig[BeansEnv][1]["engine"] == "arangodb" then
209+
SetupArangoDB(BeansEnv)
209210
ArangoDB_DBMigrate()
210-
elseif DBConfig["engine"] == "sqlite" then
211+
elseif DBConfig[BeansEnv][1]["engine"] == "sqlite" then
211212
Sqlite_DBMigrate()
212213
end
213214
end
214215

215216
if arg[1] == "db:rollback" then
216-
if DBConfig["engine"] == "arangodb" then
217-
local latest_version = Adb.primary.Aql("FOR m IN migrations SORT TO_NUMBER(m._key) DESC LIMIT 1 RETURN m").result[1]
217+
if DBConfig[BeansEnv][1]["engine"] == "arangodb" then
218+
SetupArangoDB(BeansEnv)
219+
local latest_version = Adb.primary:Aql("FOR m IN migrations SORT TO_NUMBER(m._key) DESC LIMIT 1 RETURN m").result[1]
218220
if latest_version.filename ~= "0" then
219221
print("Processing " .. latest_version.filename)
220222
local migration = require(string.gsub(latest_version.filename, ".lua", ""))
@@ -224,7 +226,7 @@ if arg[1] == "db:rollback" then
224226
else
225227
print("Nothing to rollback!")
226228
end
227-
elseif DBConfig["engine"] == "sqlite" then
229+
elseif DBConfig[BeansEnv][1]["engine"] == "sqlite" then
228230
local sqlite3 = require "lsqlite3"
229231
local db = sqlite3.open(DBConfig[BeansEnv]["db_name"] .. ".sqlite3")
230232
local latest_version = ""

0 commit comments

Comments
 (0)