Class: Julewire::Core::Fields::FieldStack

Inherits:
Object
  • Object
show all
Defined in:
lib/julewire/core/fields/field_stack.rb

Overview

Immutable layers keep snapshots stable while each stack tracks only the current head and snapshot cache.

Instance Method Summary collapse

Constructor Details

#initialize(fields = nil, delete_paths: false, source: nil) ⇒ FieldStack

Returns a new instance of FieldStack.



125
126
127
128
129
# File 'lib/julewire/core/fields/field_stack.rb', line 125

def initialize(fields = nil, delete_paths: false, source: nil)
  @source = source
  @delete_paths_enabled = delete_paths
  add(fields)
end

Instance Method Details

#add(fields = nil, owned: false, **keyword_fields) ⇒ Object



149
150
151
152
153
154
155
# File 'lib/julewire/core/fields/field_stack.rb', line 149

def add(fields = nil, owned: false, **keyword_fields)
  fields = field_input(fields, keyword_fields, owned: owned)
  return if fields.empty?

  @source = Layer.fields(@source, fields)
  invalidate_snapshot!
end

#branchObject



137
138
139
# File 'lib/julewire/core/fields/field_stack.rb', line 137

def branch
  self.class.new(delete_paths: @delete_paths_enabled, source: @source)
end

#delete(path) ⇒ Object



157
158
159
160
161
162
163
# File 'lib/julewire/core/fields/field_stack.rb', line 157

def delete(path)
  return if path.empty?
  return unless @delete_paths_enabled

  @source = Layer.delete_paths(@source, [path])
  invalidate_snapshot!
end

#snapshotObject



131
132
133
134
135
# File 'lib/julewire/core/fields/field_stack.rb', line 131

def snapshot
  return @snapshot if @snapshot

  @snapshot = @source ? @source.snapshot : EMPTY_HASH
end

#value_for(key, default:) ⇒ Object



141
142
143
144
145
146
147
# File 'lib/julewire/core/fields/field_stack.rb', line 141

def value_for(key, default:)
  key = Internal.normalize_key(key)
  value = source_value_for(key)
  return default if value.equal?(MISSING)

  value
end

#with(fields = nil, owned: false, **keyword_fields) ⇒ Object



165
166
167
168
169
170
# File 'lib/julewire/core/fields/field_stack.rb', line 165

def with(fields = nil, owned: false, **keyword_fields, &)
  fields = field_input(fields, keyword_fields, owned: owned)
  return yield if fields.empty?

  with_layer(fields, &)
end

#without(path) ⇒ Object

Raises:

  • (ArgumentError)


172
173
174
175
176
177
178
# File 'lib/julewire/core/fields/field_stack.rb', line 172

def without(path, &)
  raise ArgumentError, "field path is required" if path.empty?

  return yield unless @delete_paths_enabled

  with_delete_layer([path], &)
end