Class: Tina4::Frond::LoopContext

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

Overview

-- Lazy context overlay for for-loops (avoids full Hash#dup) --

Instance Method Summary collapse

Constructor Details

#initialize(parent) ⇒ LoopContext

Returns a new instance of LoopContext.



188
189
190
191
# File 'lib/tina4/frond.rb', line 188

def initialize(parent)
  @parent = parent
  @local = {}
end

Instance Method Details

#[](key) ⇒ Object



193
194
195
# File 'lib/tina4/frond.rb', line 193

def [](key)
  @local.key?(key) ? @local[key] : @parent[key]
end

#[]=(key, value) ⇒ Object



197
198
199
# File 'lib/tina4/frond.rb', line 197

def []=(key, value)
  @local[key] = value
end

#dupObject



232
233
234
235
236
# File 'lib/tina4/frond.rb', line 232

def dup
  copy = LoopContext.new(@parent)
  @local.each { |k, v| copy[k] = v }
  copy
end

#each(&block) ⇒ Object



244
245
246
# File 'lib/tina4/frond.rb', line 244

def each(&block)
  to_h.each(&block)
end

#fetch(key, *args, &block) ⇒ Object



207
208
209
210
211
212
213
214
215
216
217
218
219
# File 'lib/tina4/frond.rb', line 207

def fetch(key, *args, &block)
  if @local.key?(key)
    @local[key]
  elsif @parent.key?(key)
    @parent[key]
  elsif block
    yield key
  elsif !args.empty?
    args[0]
  else
    raise KeyError, "key not found: #{key.inspect}"
  end
end

#is_a?(klass) ⇒ Boolean

Returns:

  • (Boolean)


252
253
254
# File 'lib/tina4/frond.rb', line 252

def is_a?(klass)
  klass == Hash || super
end

#key?(key) ⇒ Boolean Also known as: include?, has_key?

Returns:

  • (Boolean)


201
202
203
# File 'lib/tina4/frond.rb', line 201

def key?(key)
  @local.key?(key) || @parent.key?(key)
end

#keysObject



256
257
258
# File 'lib/tina4/frond.rb', line 256

def keys
  (@parent.is_a?(LoopContext) ? @parent.keys : @parent.keys) | @local.keys
end

#merge(other) ⇒ Object



221
222
223
224
225
# File 'lib/tina4/frond.rb', line 221

def merge(other)
  dup_hash = to_h
  dup_hash.merge!(other)
  dup_hash
end

#merge!(other) ⇒ Object



227
228
229
230
# File 'lib/tina4/frond.rb', line 227

def merge!(other)
  other.each { |k, v| @local[k] = v }
  self
end

#respond_to_missing?(name, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


248
249
250
# File 'lib/tina4/frond.rb', line 248

def respond_to_missing?(name, include_private = false)
  @parent.respond_to?(name, include_private) || super
end

#to_hObject



238
239
240
241
242
# File 'lib/tina4/frond.rb', line 238

def to_h
  h = @parent.is_a?(LoopContext) ? @parent.to_h : @parent.dup
  @local.each { |k, v| h[k] = v }
  h
end