Class: Panda::Core::ChartkickAssetMiddleware

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

Overview

Serves Chartkick vendor JS files (Chart.bundle.js, chartkick.js) from the chartkick gem's vendor directory at /panda-core-assets/chartkick/*.

Constant Summary collapse

CHARTKICK_PATH_PREFIX =
"/panda-core-assets/chartkick/"
ALLOWED_FILES =
%w[Chart.bundle.js chartkick.js].freeze

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ ChartkickAssetMiddleware

Returns a new instance of ChartkickAssetMiddleware.



152
153
154
155
# File 'lib/panda/core/middleware.rb', line 152

def initialize(app)
  @app = app
  @vendor_root = Pathname.new(Gem.loaded_specs["chartkick"].gem_dir).join("vendor/assets/javascripts")
end

Instance Method Details

#call(env) ⇒ Object



157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/panda/core/middleware.rb', line 157

def call(env)
  path = Rack::Utils.unescape_path(env[Rack::PATH_INFO])

  if path.start_with?(CHARTKICK_PATH_PREFIX)
    filename = path.delete_prefix(CHARTKICK_PATH_PREFIX)
    return @app.call(env) unless ALLOWED_FILES.include?(filename)

    file_path = @vendor_root.join(filename)
    return @app.call(env) unless file_path.file?

    content = File.binread(file_path)
    cache = Rails.env.local? ? "no-cache, no-store, must-revalidate" : "public, max-age=31536000"

    [200, {
      "Content-Type" => "application/javascript; charset=utf-8",
      "Content-Length" => content.bytesize.to_s,
      "Cache-Control" => cache
    }, [content]]
  else
    @app.call(env)
  end
end