Sha256: 8ad8fe118ae8eb82efc8b1d7ea711291041313a0f5c7d0b2f6828b5f3be0de23

Contents?: true

Size: 1.66 KB

Versions: 2

Compression:

Stored size: 1.66 KB

Contents

require 'hanami/action/cache/cache_control'

module Hanami
  module Action
    module Cache

      # Module with Expires logic
      #
      # @since 0.3.0
      # @api private
      module Expires

        # The HTTP header for Expires
        #
        # @since 0.3.0
        # @api private
        HEADER = 'Expires'.freeze

        def self.included(base)
          base.extend ClassMethods
        end

        module ClassMethods
          def expires(amount, *values)
            @expires_directives ||= Directives.new(amount, *values)
          end

          def expires_directives
            @expires_directives || Object.new.tap do |null_object|
              def null_object.headers
                Hash.new
              end
            end
          end
        end

        # Finalize the response including default cache headers into the response
        #
        # @since 0.3.0
        # @api private
        #
        # @see Hanami::Action#finish
        def finish
          super
          headers.merge!(self.class.expires_directives.headers) unless headers.include? HEADER
        end

        # Class which stores Expires directives
        #
        # @since 0.3.0
        #
        # @api private
        #
        class Directives
          def initialize(amount, *values)
            @amount = amount
            @cache_control = Hanami::Action::Cache::CacheControl::Directives.new(*(values << { max_age: amount }))
          end

          def headers
            { HEADER => time.httpdate }.merge(@cache_control.headers)
          end

          private

          def time
            Time.now + @amount.to_i
          end
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
hanami-controller-0.6.1 lib/hanami/action/cache/expires.rb
hanami-controller-0.6.0 lib/hanami/action/cache/expires.rb