Class: ObjectForge::Molds::HashMold

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

Overview

Mold for constructing Hashes.

Since:

  • 0.2.0

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(default_value = nil) {|hash, key| ... } ⇒ HashMold

Initialize new HashMold with default value or default proc to be assigned to each produced hash.

The same exact objects are used for each hash. It is not advised to use mutable objects as default values. Be aware that using a default proc with assignment is inherently not safe, see this Ruby issue: bugs.ruby-lang.org/issues/19237.

Parameters:

  • default_value (Any) (defaults to: nil)

Yield Parameters:

  • hash (Hash)
  • key (Any)

Yield Returns:

  • (Any)

See Also:

  • Hash.new

Since:

  • 0.2.0



34
35
36
37
# File 'lib/object_forge/molds/hash_mold.rb', line 34

def initialize(default_value = nil, &default_proc)
  @default = default_value
  @default_proc = default_proc
end

Instance Attribute Details

#defaultAny? (readonly)

Default value to be assigned to each produced hash.

Returns:

  • (Any, nil)

Since:

  • 0.2.0



14
15
16
# File 'lib/object_forge/molds/hash_mold.rb', line 14

def default
  @default
end

#default_procProc? (readonly)

Default proc to be assigned to each produced hash.

Returns:

  • (Proc, nil)

Since:

  • 0.2.0



17
18
19
# File 'lib/object_forge/molds/hash_mold.rb', line 17

def default_proc
  @default_proc
end

Instance Method Details

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

Build a new hash using forged.[].

Parameters:

  • forged (Class)

    Hash or a subclass of Hash

  • attributes (Hash{Symbol => Any})

Returns:

  • (Hash)

See Also:

  • Hash.[]

Since:

  • 0.2.0



46
47
48
49
50
51
# File 'lib/object_forge/molds/hash_mold.rb', line 46

def call(forged:, attributes:, **_)
  hash = forged[attributes]
  hash.default = @default if @default
  hash.default_proc = @default_proc if @default_proc
  hash
end