Sha256: 16b17ff0f4f83683bc9859c115cc7e57bd09cf03103edfff42dac4ca54841fde

Contents?: true

Size: 1.73 KB

Versions: 6

Compression:

Stored size: 1.73 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.class_eval do
            extend ClassMethods
            @expires_directives = nil
          end
        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

6 entries across 6 versions & 1 rubygems

Version Path
hanami-controller-1.0.0.beta2 lib/hanami/action/cache/expires.rb
hanami-controller-1.0.0.beta1 lib/hanami/action/cache/expires.rb
hanami-controller-0.8.1 lib/hanami/action/cache/expires.rb
hanami-controller-0.8.0 lib/hanami/action/cache/expires.rb
hanami-controller-0.7.1 lib/hanami/action/cache/expires.rb
hanami-controller-0.7.0 lib/hanami/action/cache/expires.rb