Sha256: fc9b05c7e7e5217d20bfa5e77517d4b09b27963ca08e00690607377589fb8257

Contents?: true

Size: 1.42 KB

Versions: 9

Compression:

Stored size: 1.42 KB

Contents

require 'heartcheck/caching_app/cache'

# A rack middleware to wrap around {Heartcheck::App} in a cache
#   Mount an instance of this class passing an app or `use` this in Rack.
#   This accepts an optional ttl for the cache that defaults to 300 seconds.
module Heartcheck
  class CachingApp
    # Creates an instance of the middleware
    #
    # @param app [Heartcheck:App] the Rack app to wrap around
    # @param ttl [Integer] the time to cache the results in seconds
    # @param cache [Heartcheck::CachingApp::Cache] the cache instance to use
    #   The cache will be created on first use if not supplied
    #
    # @return [#call] rack compatible middleware
    def initialize(app, ttl = 300, cache = nil)
      @app = app
      @ttl = ttl
      @cache = cache
    end

    # Invokes the middleware
    #
    # @param env [Hash] the rack request/environment
    # @return [Array] a rack compatible response
    def call(env)
      req = Rack::Request.new(env)
      controller = Heartcheck::App::ROUTE_TO_CONTROLLER[req.path_info]

      if controller && (result = cache.result(controller))
        [200, { 'Content-type' => 'application/json' }, [result]]
      else
        @app.call(env)
      end
    end

    protected

    def cache
      @cache ||= start_cache(@ttl)
    end

    def start_cache(ttl)
      Heartcheck::CachingApp::Cache.new(Heartcheck::App::ROUTE_TO_CONTROLLER
        .values.uniq, ttl).tap(&:start)
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
heartcheck-2.0.0 lib/heartcheck/caching_app.rb
heartcheck-1.6.0 lib/heartcheck/caching_app.rb
heartcheck-1.5.1 lib/heartcheck/caching_app.rb
heartcheck-1.5.0 lib/heartcheck/caching_app.rb
heartcheck-1.4.0 lib/heartcheck/caching_app.rb
heartcheck-1.3.0 lib/heartcheck/caching_app.rb
heartcheck-1.2.2 lib/heartcheck/caching_app.rb
heartcheck-1.2.1 lib/heartcheck/caching_app.rb
heartcheck-1.2.0 lib/heartcheck/caching_app.rb