Class: Blaml::MetaHash

Inherits:
MetaNode show all
Defined in:
lib/blaml/meta.rb

Overview

Wraps Hash instances with metadata.

Instance Attribute Summary

Attributes inherited from MetaNode

#value

Instance Method Summary collapse

Methods inherited from MetaNode

#==, #initialize, #method_missing, #to_yaml

Constructor Details

This class inherits a constructor from Blaml::MetaNode

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class Blaml::MetaNode

Instance Method Details

#[](key) ⇒ Object

Access a value of the wrapped hash.



120
121
122
# File 'lib/blaml/meta.rb', line 120

def [] key
  @value.each{|k,v| return v if k == key}
end

#[]=(key, val) ⇒ Object

Assign a value of the wrapped hash.



128
129
130
# File 'lib/blaml/meta.rb', line 128

def []= key, val
  @value.each{|k,v| @value[k] = val and return if k == key}
end

#merge(hash) ⇒ Object

Create a new MetaHash merged with the given hash or metahash.



150
151
152
153
154
155
156
157
158
159
# File 'lib/blaml/meta.rb', line 150

def merge hash
  clone = @value.dup
  hash.each do |k,v|
    key = clone.keys.find{|vk| vk == k || k == vk } || k
    clone.delete key
    clone[k] = v
  end

  clone
end

#merge!(hash) ⇒ Object

Merge with and modify the wrapped hash.



136
137
138
139
140
141
142
143
144
# File 'lib/blaml/meta.rb', line 136

def merge! hash
  hash.each do |k,v|
    key = @value.keys.find{|vk| vk == k || k == vk } || k
    @value.delete key
    @value[k] = v
  end

  self
end

#metaObject

Returns the child metadata with the most recent change.



165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
# File 'lib/blaml/meta.rb', line 165

def meta
  meta     = nil
  path_key = nil

  @value.each do |key, val|
    if val.respond_to? :meta
      if !meta ||
        meta && val.meta && val.meta[:updated_at] > meta[:updated_at]
        meta = val.meta.dup
        path_key = key
      end
    end

    if key.respond_to? :meta
      if !meta ||
        meta && val.meta && key.meta[:updated_at] > meta[:updated_at]
        meta = key.meta.dup
      end
    end
  end

  (meta[:path] ||= []).unshift path_key if meta && path_key

  meta
end

#to_valueObject

Strips MetaNode wrapper from the value and calls to_value on all hash elements.



196
197
198
199
200
201
202
203
204
205
206
207
# File 'lib/blaml/meta.rb', line 196

def to_value
  clone = Hash.new

  @value.each do |k, v|
    key = k.respond_to?(:to_value) ? k.to_value : k
    val = v.respond_to?(:to_value) ? v.to_value : v

    clone[key] = val
  end

  clone
end