-
Notifications
You must be signed in to change notification settings - Fork 152
/
Copy pathmiddleware.rb
52 lines (44 loc) · 1.07 KB
/
middleware.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# typed: strict
require "js_routes/types"
module JsRoutes
# A Rack middleware that automatically updates routes file
# whenever routes.rb is modified
#
# Inspired by
# https://github.com/fnando/i18n-js/blob/main/lib/i18n/js/middleware.rb
class Middleware
include JsRoutes::Types
include RackApp
extend T::Sig
sig { params(app: T.untyped).void }
def initialize(app)
@app = app
@routes_file = T.let(Rails.root.join("config/routes.rb"), Pathname)
@mtime = T.let(nil, T.nilable(Time))
end
sig { override.params(env: StringHash).returns(UntypedArray) }
def call(env)
update_js_routes
@app.call(env)
end
protected
sig { void }
def update_js_routes
new_mtime = routes_mtime
unless new_mtime == @mtime
regenerate
@mtime = new_mtime
end
end
sig { void }
def regenerate
JsRoutes.generate!(typed: true)
end
sig { returns(T.nilable(Time)) }
def routes_mtime
File.mtime(@routes_file)
rescue Errno::ENOENT
nil
end
end
end