Class: Samsa::Transforms

Inherits:
Object
  • Object
show all
Defined in:
lib/samsa.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeTransforms

Returns a new instance of Transforms.



29
30
31
32
# File 'lib/samsa.rb', line 29

def initialize
  @transforms = []
  @lazy_transforms = []
end

Instance Attribute Details

#transformsObject (readonly)

Returns the value of attribute transforms.



34
35
36
# File 'lib/samsa.rb', line 34

def transforms
  @transforms
end

Instance Method Details

#conditional(inputs) ⇒ Object



50
51
52
53
54
# File 'lib/samsa.rb', line 50

def conditional(inputs)
  @lazy_transforms << lambda do |input|
    yield(*Array[*inputs].map { |i| input.dig(*extract_path(i)) })
  end
end

#extract_path(path_str) ⇒ Object



56
57
58
59
# File 'lib/samsa.rb', line 56

def extract_path(path_str)
  path = path_str.split(".").map { |s| s.to_i.to_s == s ? s.to_i : s.to_sym }
  Array[*path]
end

#map(from:, to:, default: nil) ⇒ Object



40
41
42
43
44
# File 'lib/samsa.rb', line 40

def map(from:, to:, default: nil)
  transform = { type: :map, from: extract_path(from), to: extract_path(to) }
  transform[:default] = default unless default.nil?
  @transforms << transform
end

#run_lazy(input) ⇒ Object



36
37
38
# File 'lib/samsa.rb', line 36

def run_lazy(input)
  @lazy_transforms.each { |t| t.call(input) }
end

#set(value, to:) ⇒ Object



46
47
48
# File 'lib/samsa.rb', line 46

def set(value, to:)
  @transforms << { type: :set, value: value, to: extract_path(to) }
end