Class: Myrr::Port::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/myrr/port/middleware.rb

Constant Summary collapse

HEADER_NAME =
"X-Token-Count"

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Middleware

Returns a new instance of Middleware.



8
9
10
# File 'lib/myrr/port/middleware.rb', line 8

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/myrr/port/middleware.rb', line 12

def call(env)
  status, headers, body_out = @app.call(env)

  if content_type_is_markdown?(headers)
    raw_body = extract_body(body_out)
    resolved_body, meta = (raw_body, env["myrr.metadata"] || {})

    if meta[:title] || meta[:description]
      resolved_body = build_frontmatter_body(resolved_body, meta)
    end

    token_count = Myrr::Tokenizer.count(resolved_body)
    headers[HEADER_NAME] = token_count.to_s
    body_out = [resolved_body]
  end

  [status, headers, body_out]
end