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.



107
108
109
110
# File 'lib/tina4/frond.rb', line 107

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

Instance Method Details

#[](key) ⇒ Object



112
113
114
# File 'lib/tina4/frond.rb', line 112

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

#[]=(key, value) ⇒ Object



116
117
118
# File 'lib/tina4/frond.rb', line 116

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

#dupObject



151
152
153
154
155
# File 'lib/tina4/frond.rb', line 151

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

#each(&block) ⇒ Object



163
164
165
# File 'lib/tina4/frond.rb', line 163

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

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



126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/tina4/frond.rb', line 126

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)


171
172
173
# File 'lib/tina4/frond.rb', line 171

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

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

Returns:

  • (Boolean)


120
121
122
# File 'lib/tina4/frond.rb', line 120

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

#keysObject



175
176
177
# File 'lib/tina4/frond.rb', line 175

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

#merge(other) ⇒ Object



140
141
142
143
144
# File 'lib/tina4/frond.rb', line 140

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

#merge!(other) ⇒ Object



146
147
148
149
# File 'lib/tina4/frond.rb', line 146

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

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

Returns:

  • (Boolean)


167
168
169
# File 'lib/tina4/frond.rb', line 167

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

#to_hObject



157
158
159
160
161
# File 'lib/tina4/frond.rb', line 157

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