Class: Reforge::Transformation::Transform::Memo

Inherits:
Object
  • Object
show all
Defined in:
lib/reforge/transformation/transform/memo.rb

Constant Summary collapse

CONSTANT_TRANSFORM =
->(_source) { :constant }.freeze
IDENTITY_TRANSFORM =
->(source) { source }.freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key_transform) ⇒ Memo

Returns a new instance of Memo.



25
26
27
28
29
30
31
32
# File 'lib/reforge/transformation/transform/memo.rb', line 25

def initialize(key_transform)
  @memo = {}
  @key_transform = Transform.new(key_transform)
rescue ArgumentError
  # TRICKY: Transform didn't like key_transform, but we want to raise an error specific to Memo, not the one
  # directly from Transform
  raise ArgumentError, "The memoize option should be true, :first, or a valid configuration hash"
end

Class Method Details

.from(memoize) ⇒ Object

TODO: here we code to the least common denominator: everything is a proc. This likely works slower than something specialized to each individual case This could be of concern since these will be called per-transform, per-source



13
14
15
16
17
18
19
20
21
22
23
# File 'lib/reforge/transformation/transform/memo.rb', line 13

def self.from(memoize)
  if memoize.is_a?(Hash) # rubocop:disable Style/CaseLikeIf:
    Memo.new(memoize[:by])
  elsif memoize == :first
    Memo.new(CONSTANT_TRANSFORM)
  elsif memoize == true
    Memo.new(IDENTITY_TRANSFORM)
  else
    raise ArgumentError, "The memoize option should be true, :first, or a valid configuration hash"
  end
end

Instance Method Details

#[](source) ⇒ Object



34
35
36
37
# File 'lib/reforge/transformation/transform/memo.rb', line 34

def [](source)
  key = @key_transform.call(source)
  @memo[key]
end

#[]=(source, value) ⇒ Object



39
40
41
42
# File 'lib/reforge/transformation/transform/memo.rb', line 39

def []=(source, value)
  key = @key_transform.call(source)
  @memo[key] = value
end