Class: Constants::ConstantLibrary::Index

Inherits:
Hash
  • Object
show all
Includes:
Stash
Defined in:
lib/constants/constant_library.rb

Overview

A hash-based Stash to index library objects.

Instance Attribute Summary collapse

Attributes included from Stash

#nil_value

Instance Method Summary collapse

Constructor Details

#initialize(exclusion_value = nil, nil_value = nil, &block) ⇒ Index

Initializes a new Index (a type of Hash).

The block is used by stash to calculate the key for stashing a given value. If the key equals the exclusion value, then the value is skipped. The new index will return nil_value for unknown keys (ie it is the default value for self) and CANNOT be stashed (see Stash).



34
35
36
37
38
39
# File 'lib/constants/constant_library.rb', line 34

def initialize(exclusion_value=nil, nil_value=nil, &block)
  super(nil_value, &nil)
  @nil_value = nil_value
  @exclusion_value = exclusion_value
  @block = block
end

Instance Attribute Details

#blockObject (readonly)

The block used to calculate keys during stash



22
23
24
# File 'lib/constants/constant_library.rb', line 22

def block
  @block
end

#exclusion_valueObject (readonly)

Indicates when values are skipped during stash



25
26
27
# File 'lib/constants/constant_library.rb', line 25

def exclusion_value
  @exclusion_value
end

Instance Method Details

#stash(values) ⇒ Object

Stashes the specified values using keys calculated by the block. Skips values when the block returns the exclusion value.

See Constants::ConstantLibrary#index_by for more details.



46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/constants/constant_library.rb', line 46

def stash(values)
  values.each_with_index do |value, index| 
    result = block.call(value)
    
    case result
    when exclusion_value then next
    when Array then super(*result)
    else super(result, value)
    end
  end
  
  self
end