Class: PgHeroAssets::Middleware

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

Overview

Catches pghero asset requests and serves them from the gem.

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Middleware

Returns a new instance of Middleware.



6
7
8
9
# File 'lib/pghero_assets/middleware.rb', line 6

def initialize(app, *)
  @app = app
  @regexp = %r{\A/(?:javascripts|images|stylesheets)/pghero}
end

Instance Method Details

#call(env) ⇒ Object



11
12
13
14
15
# File 'lib/pghero_assets/middleware.rb', line 11

def call(env)
  @regexp.match?(env[Rack::PATH_INFO]) &&
    serve(env[Rack::PATH_INFO]) ||
    @app.call(env)
end

#send_data(path) ⇒ Object



25
26
27
28
29
30
31
32
33
34
# File 'lib/pghero_assets/middleware.rb', line 25

def send_data(path)
  prepared_asset_path = PgHeroAssets.asset_root.join(path.sub(%r{^/}, ''))
  data = File.read(prepared_asset_path)
  headers = {
    'cache-control'  => 'public, max-age=86400',
    'content-length' => data.bytesize.to_s,
    'content-type'   => Rack::Mime.mime_type(File.extname(path)),
  }
  [200, headers, [data]]
end

#serve(path) ⇒ Object



17
18
19
20
21
22
23
# File 'lib/pghero_assets/middleware.rb', line 17

def serve(path)
  PgHeroAssets.prepare_assets
  send_data(path)
rescue StandardError => e
  Rails.logger.warn("PgHeroAssets::Middleware: #{e.class} #{e.message}")
  nil
end