Sha256: cd0582396fcfcecc1f4d1354de8a071e98c2341bfce1588b4a070acdfac40df5

Contents?: true

Size: 1.73 KB

Versions: 3

Compression:

Stored size: 1.73 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
      klass = self.class
      key = Digest::SHA256.hexdigest(klass.cache_key.call(self, nil).to_s)
      "#{klass.name.underscore}/#{key}"
    end

    # DSL Methods
    module ClassMethods
      # Responsible for converting our DSL options into cache store options
      CacheOptions = Struct.new(:ttl) do
        def to_store_options
          # compact is not available in Ruby <2.4 or ActiveSupport < 4, so
          # we can't use it here.
          options = {}
          options[:expires_in] = ttl if ttl
          options
        end
      end

      def cache_options
        @cache_options ||= CacheOptions.new
      end

      def cache_store(store = nil)
        if store
          @cache_store = store
        else
          @cache_store ||= if defined?(Rails)
                             Rails.cache
                           else
                             ActiveSupport::Cache::MemoryStore.new
                           end
        end
      end

      def cache_ttl(ttl = nil)
        if ttl
          cache_options.ttl = ttl
        else
          cache_options.ttl
        end
      end

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

      def execute(flow)
        cache_store.fetch(flow.cache_key, cache_options.to_store_options) do
          super(flow)
          raise FlowFailedException, flow if flow.errors.any?
          flow
        end
      rescue FlowFailedException
        flow
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
business_flow-0.8.2 lib/business_flow/cacheable.rb
business_flow-0.8.1 lib/business_flow/cacheable.rb
business_flow-0.8.0 lib/business_flow/cacheable.rb