Class: RailsPulse::Middleware::AssetServer

Inherits:
Rack::Static
  • Object
show all
Defined in:
lib/rails_pulse/middleware/asset_server.rb

Constant Summary collapse

MIME_TYPES =
{
  ".css" => "text/css",
  ".js" => "application/javascript",
  ".map" => "application/json",
  ".svg" => "image/svg+xml"
}.freeze

Instance Method Summary collapse

Constructor Details

#initialize(app, root, options = {}) ⇒ AssetServer

Returns a new instance of AssetServer.



13
14
15
16
17
18
# File 'lib/rails_pulse/middleware/asset_server.rb', line 13

def initialize(app, root, options = {})
  @logger = Rails.logger if defined?(Rails)
  # Rack::Static expects (app, options) where options[:root] is the root path
  options = options.merge(root: root) if root.is_a?(String) || root.is_a?(Pathname)
  super(app, options)
end

Instance Method Details

#call(env) ⇒ Object



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
# File 'lib/rails_pulse/middleware/asset_server.rb', line 20

def call(env)
  # Only handle requests for Rails Pulse assets
  unless rails_pulse_asset_request?(env)
    return @app.call(env)
  end

  # Log asset requests for debugging
  @logger&.debug "[Rails Pulse] Asset request: #{env['PATH_INFO']}"

  # Set proper MIME type based on file extension
  set_content_type(env)

  # Call parent Rack::Static with error handling
  begin
    status, headers, body = super(env)

    # Add immutable cache headers for successful responses
    if status == 200
      headers.merge!(cache_headers)
      @logger&.debug "[Rails Pulse] Asset served successfully: #{env['PATH_INFO']}"
    elsif status == 404
      log_missing_asset(env["PATH_INFO"]) if @logger
    end

    [ status, headers, body ]
  rescue => e
    log_asset_error(env["PATH_INFO"], e) if @logger
    @app.call(env)
  end
end