Module: Dry::Core::Constants

Included in:
Dry::Core, ClassAttributes, Container
Defined in:
lib/dry/core/constants.rb

Overview

A list of constants you can use to avoid memory allocations or identity checks.

Examples:

Just include this module to your class or module

class Foo
  include Dry::Core::Constants
  def call(value = EMPTY_ARRAY)
     value.map(&:to_s)
  end
end

Constant Summary collapse

EMPTY_ARRAY =

An empty array

[].freeze
EMPTY_HASH =

An empty hash

{}.freeze
EMPTY_OPTS =

An empty list of options

{}.freeze
EMPTY_SET =

An empty set

::Set.new.freeze
EMPTY_STRING =

An empty string

""
IDENTITY =

Identity function

(-> x { x }).freeze
Undefined =

A special value you can use as a default to know if no arguments were passed to the method

Examples:

def method(value = Undefined)
  if Undefined.equal?(value)
    puts 'no args'
  else
    puts value
  end
end
Object.new.tap do |undefined|
  # @api private
  Self = -> { Undefined } # rubocop:disable Lint/ConstantDefinitionInBlock

  # @api public
  def undefined.to_s
    "Undefined"
  end

  # @api public
  def undefined.inspect
    "Undefined"
  end

  # Pick a value, if the first argument is not Undefined, return it back,
  # otherwise return the second arg or yield the block.
  #
  # @example
  #   def method(val = Undefined)
  #     1 + Undefined.default(val, 2)
  #   end
  #
  def undefined.default(x, y = self)
    if equal?(x)
      if equal?(y)
        yield
      else
        y
      end
    else
      x
    end
  end

  # Map a non-undefined value
  #
  # @example
  #   def add_five(val = Undefined)
  #     Undefined.map(val) { |x| x + 5 }
  #   end
  #
  def undefined.map(value)
    if equal?(value)
      self
    else
      yield(value)
    end
  end

  # @api public
  def undefined.dup
    self
  end

  # @api public
  def undefined.clone
    self
  end

  # @api public
  def undefined.coalesce(*args)
    args.find(Self) { |x| !equal?(x) }
  end
end.freeze

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object



108
109
110
111
112
113
114
# File 'lib/dry/core/constants.rb', line 108

def self.included(base)
  super

  constants.each do |const_name|
    base.const_set(const_name, const_get(const_name))
  end
end