Sha256: 60173c3d8e75c2432937ca803e7373de4fe9052cfd5c0041b5c073a1a27cd52e

Contents?: true

Size: 1.7 KB

Versions: 11

Compression:

Stored size: 1.7 KB

Contents

require 'rack/static'

module Hanami
  # Serve static assets in deployment environments (production, staging) where
  # the stack doesn't include a web server.
  #
  # Web servers like Nginx are the ideal candidate to serve static assets.
  # They are faster than Ruby application servers (eg. Puma) and they should be
  # always preferred for this specific task.
  #
  # But there are some PaaS that don't allow to use web servers in front of Ruby
  # web applications. A classical example is Heroku, which requires the web
  # application to serve static assets.
  #
  # Hanami::Static is designed for this specific scenario.
  #
  # To enable it set the env variable `SERVE_STATIC_ASSETS` on `true`.
  #
  # NOTE: Please remember to precompile the assets at the deploy time with
  # `bundle exec hanami assets precompile`.
  #
  # @since 0.6.0
  # @api private
  #
  # @see http://www.rubydoc.info/gems/rack/Rack/Static
  class Static < ::Rack::Static
    # @since 0.8.0
    # @api private
    MAX_AGE      = 60 * 60 * 24 * 365 # One year

    # @since 0.8.0
    # @api private
    HEADER_RULES = [[:all, { 'Cache-Control' => "public, max-age=#{MAX_AGE}" }]].freeze

    # @since 0.8.0
    # @api private
    URL_PREFIX = '/'.freeze

    # @since 0.6.0
    # @api private
    def initialize(app, root: Hanami.public_directory, header_rules: HEADER_RULES)
      super(app, urls: _urls(root), root: root, header_rules: header_rules)
    end

    private

    # @since 0.8.0
    # @api private
    def _urls(root)
      return [] unless root.exist?

      asset_files = Dir.chdir(root) do
        Dir['**/*'].select { |path| File.file? path }
      end
      Hash[asset_files.map { |entry| ["#{URL_PREFIX}#{entry}", entry] }]
    end
  end
end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
hanami-1.2.0 lib/hanami/static.rb
hanami-1.2.0.rc2 lib/hanami/static.rb
hanami-1.2.0.rc1 lib/hanami/static.rb
hanami-1.2.0.beta2 lib/hanami/static.rb
hanami-1.2.0.beta1 lib/hanami/static.rb
hanami-1.1.1 lib/hanami/static.rb
hanami-1.1.0 lib/hanami/static.rb
hanami-1.1.0.rc1 lib/hanami/static.rb
hanami-1.1.0.beta3 lib/hanami/static.rb
hanami-1.1.0.beta2 lib/hanami/static.rb
hanami-1.1.0.beta1 lib/hanami/static.rb