Class: ObjectForge::Molds::StructMold

Inherits:
Object
  • Object
show all
Defined in:
lib/object_forge/molds/struct_mold.rb

Overview

Mold for building Structs.

Supports all variations of keyword_init.

Since:

  • 0.2.0

Constant Summary collapse

RUBY_FEATURE_AUTO_KEYWORDS =

Does Struct automatically use keyword initialization when keyword_init is not specified / nil?

Returns:

  • (Boolean)

Since:

  • 0.2.0

(::Struct.new(:a, :b).new(a: 1, b: 2).a == 1)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(lax: true) ⇒ StructMold

Returns a new instance of StructMold.

Parameters:

  • lax (Boolean) (defaults to: true)

    whether to work around argument hashes with extra keys (when keyword_init is false, workaround always happens for technical reasons)

    • if true, arguments can contain extra keys, but building is slower;

    • if false, building may raise an error if extra keys are present;

Since:

  • 0.2.0



29
30
31
# File 'lib/object_forge/molds/struct_mold.rb', line 29

def initialize(lax: true)
  @lax = lax
end

Instance Attribute Details

#laxBoolean (readonly) Also known as: lax?

Whether to work around argument hashes with extra keys.

Returns:

  • (Boolean)

Since:

  • 0.2.0



21
22
23
# File 'lib/object_forge/molds/struct_mold.rb', line 21

def lax
  @lax
end

Instance Method Details

#call(forged:, attributes:, **_) ⇒ Struct

Instantiate forged struct with a hash of attributes.

Parameters:

  • forged (Class)

    a subclass of Struct

  • attributes (Hash{Symbol => Any})

Returns:

  • (Struct)

Since:

  • 0.2.0



38
39
40
41
42
43
44
45
46
# File 'lib/object_forge/molds/struct_mold.rb', line 38

def call(forged:, attributes:, **_)
  if forged.keyword_init?
    lax ? forged.new(attributes.slice(*forged.members)) : forged.new(attributes)
  elsif forged.keyword_init? == false
    forged.new(*attributes.values_at(*forged.members))
  else
    build_struct_with_unspecified_keyword_init(forged, attributes)
  end
end