Module: Root::Minimap

Included in:
Manifest
Defined in:
lib/root/minimap.rb

Overview

Minimap adds minimization and search methods to an array of paths (see Utils.minimize and Utils.minimal_match?).

paths = %w{
  path/to/file-0.1.0.txt 
  path/to/file-0.2.0.txt
  path/to/another_file.txt
}
paths.extend Root::Minimap

paths.minimatch('file')             # => 'path/to/file-0.1.0.txt'
paths.minimatch('file-0.2.0')       # => 'path/to/file-0.2.0.txt'
paths.minimatch('another_file')     # => 'path/to/another_file.txt'

More generally, Minimap may extend any object responding to each. Override the minikey method to convert objects into paths.

class ConstantMap < Array
  include Root::Minimap

  def minikey(const)
    const.underscore
  end
end 

constants = ConstantMap[Root::Minimap, Root]
constants.minimatch('root')         # => Root
constants.minimatch('minimap')      # => Root::Minimap

Instance Method Summary collapse

Instance Method Details

#minimapObject

Provides a minimized map of the entries using keys provided minikey.

paths = %w{
  path/to/file-0.1.0.txt 
  path/to/file-0.2.0.txt
  path/to/another_file.txt
}.extend Root::Minimap

paths.minimap
# => [
# ['file-0.1.0',  'path/to/file-0.1.0.txt'],
# ['file-0.2.0',  'path/to/file-0.2.0.txt'],
# ['another_file','path/to/another_file.txt']]


50
51
52
53
54
55
56
57
58
59
# File 'lib/root/minimap.rb', line 50

def minimap
  hash = {}
  map = []
  each {|entry| map << (hash[minikey(entry)] = [entry]) }
  Utils.minimize(hash.keys) do |key, mini_key|
    hash[key].unshift mini_key
  end
  
  map
end

#minimatch(key) ⇒ Object

Returns the first entry whose minikey mini-matches the input, or nil if no such entry exists.

paths = %w{
  path/to/file-0.1.0.txt 
  path/to/file-0.2.0.txt
  path/to/another_file.txt
}.extend Root::Minimap

paths.minimatch('file-0.2.0')       # => 'path/to/file-0.2.0.txt'
paths.minimatch('file-0.3.0')       # => nil


73
74
75
76
77
78
# File 'lib/root/minimap.rb', line 73

def minimatch(key)
  each do |entry| 
    return entry if Utils.minimal_match?(minikey(entry), key)
  end
  nil
end