Sha256: 82eb5fc173a5d87462cec1164a87eeb770e366665a5f65679c0737c867d0aa8e

Contents?: true

Size: 1.73 KB

Versions: 2

Compression:

Stored size: 1.73 KB

Contents

# frozen_string_literal: true

require "dry/effects/provider"
require "dry/effects/providers/current_time"

module Dry
  module Effects
    module Providers
      class Timestamp < Provider[:timestamp]
        include Dry::Equalizer(:round)
        include CurrentTime::TimeGenetators

        Locate = Effect.new(type: :timestamp, name: :locate)

        option :round, default: -> { Undefined }

        attr_reader :generator

        # Yield the block with the handler installed
        #
        # @api private
        def call(*args)
          gen, options = value_with_options_from_args(args)
          @generator = build_generator(gen, **options)
          yield
        end

        def timestamp(round_to: Undefined, **options)
          time = generator.(**options)

          round = Undefined.coalesce(round_to, self.round)

          if Undefined.equal?(round)
            time
          else
            time.round(round)
          end
        end

        # Locate handler in the stack
        #
        # @return [Provider]
        # @api private
        def locate
          self
        end

        private

        # @return [Proc] time generator
        # @api private
        def build_generator(generator, step: Undefined, initial: Undefined, overridable: false)
          if overridable
            parent = ::Dry::Effects.yield(Locate) { nil }
          else
            parent = nil
          end

          if !parent.nil?
            -> **options { parent.timestamp(**options) }
          elsif !Undefined.equal?(generator)
            generator
          elsif !Undefined.equal?(step)
            IncrementingTimeGenerator.(initial, step)
          else
            RunningTimeGenerator.()
          end
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
dry-effects-0.3.0 lib/dry/effects/providers/timestamp.rb
dry-effects-0.2.0 lib/dry/effects/providers/timestamp.rb