Sha256: 99d0b6c649b7172f608269c023b8907a1f1d7897abd7fa400f0691256da61940

Contents?: true

Size: 1.25 KB

Versions: 1

Compression:

Stored size: 1.25 KB

Contents

module BusinessFlow
  # Extends the DSL to support caching of completed processes
  module Cacheable
    def self.included(klass)
      klass.extend(ClassMethods)
    end

    def cache_key
      "#{self.class.name}/#{self.class.cache_key.call(self, nil)}"
    end

    # DSL Methods
    module ClassMethods
      def cache_store(store = nil)
        if store
          @cache_store = store
        else
          @cache_store ||= ActiveSupport::Cache::MemoryStore.new
        end
      end

      def cache_ttl(ttl = nil)
        if ttl
          @cache_ttl = ttl
        else
          @cache_ttl
        end
      end

      def cache_key(key = nil)
        if key
          @cache_key = Callable.new(key, self)
        else
          @cache_key ||= Callable.new(:parameter_object, self)
        end
      end

      # TODO: Make this some kind of private helper
      def cache_options
        # compact is not available in Ruby <2.4 or ActiveSupport < 4, so
        # we can't use it here.
        options = {}
        ttl = cache_ttl
        options[:expires_in] = ttl if ttl
        options
      end

      def call(*args)
        ret = new(*args)
        cache_store.fetch(ret.cache_key, cache_options) do
          ret.tap(&:call)
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
business_flow-0.5.1 lib/business_flow/cacheable.rb