Module: Lotus::Utils::Duplicable

Defined in:
lib/lotus/utils/duplicable.rb

Overview

Safe dup logic

Since:

  • 0.6.0

Class Method Summary collapse

Class Method Details

.dup(value, &blk) ⇒ Object

Duplicates the given value.

It accepts a block to customize the logic.

The following types aren’t duped:

* <tt>NilClass</tt>
* <tt>FalseClass</tt>
* <tt>TrueClass</tt>
* <tt>Symbol</tt>
* <tt>Numeric</tt>

All the other types are duped via #dup

Examples:

Basic Usage With Types That Can’t Be Duped

require 'lotus/utils/duplicable'

object = 23
puts object.object_id # => 47

result = Lotus::Utils::Duplicable.dup(object)

puts result           # => 23
puts result.object_id # => 47 - Same object, because numbers can't be duped

Basic Usage With Types That Can Be Duped

require 'lotus/utils/duplicable'

object = "hello"
puts object.object_id # => 70172661782360

result = Lotus::Utils::Duplicable.dup(object)

puts result           # => "hello"
puts result.object_id # => 70172671467020 – Different object

Custom Logic

require 'lotus/utils/duplicable'
require 'lotus/utils/hash'

hash = { a: 1 }
puts hash.object_id # => 70207105061680

result = Lotus::Utils::Duplicable.dup(hash) do |value|
  case value
  when Lotus::Utils::Hash
    value.deep_dup
  when ::Hash
    Lotus::Utils::Hash.new(value).deep_dup.to_h
  end
end

puts result           # => "{:a=>1}"
puts result.object_id # => 70207105185500 – Different object

Parameters:

  • value (Object)

    the value to duplicate

  • blk (Proc)

    the optional block to customize the logic

Returns:

  • (Object)

    the duped value

Since:

  • 0.6.0



68
69
70
71
72
73
74
75
76
77
# File 'lib/lotus/utils/duplicable.rb', line 68

def self.dup(value, &blk)
  case value
  when NilClass, FalseClass, TrueClass, Symbol, Numeric
    value
  when v = blk && blk.call(value)
    v
  else
    value.dup
  end
end