Class: Rack::Mount::Multimap

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/mount/multimap.rb

Overview

:nodoc:

Instance Method Summary collapse

Constructor Details

#initialize(default = []) ⇒ Multimap

Returns a new instance of Multimap.



3
4
5
# File 'lib/rack/mount/multimap.rb', line 3

def initialize(default = [])
  @hash = Hash.new(default)
end

Instance Method Details

#[](*keys) ⇒ Object



46
47
48
49
50
51
52
53
# File 'lib/rack/mount/multimap.rb', line 46

def [](*keys)
  i, l, r, k = 0, keys.length, self, self.class
  while r.is_a?(k)
    r = i < l ? r.hash[keys[i]] : r.default
    i += 1
  end
  r
end

#average_heightObject



59
60
61
62
# File 'lib/rack/mount/multimap.rb', line 59

def average_height
  lengths = containers_with_default.map { |e| e.length }
  lengths.inject(0) { |sum, len| sum += len }.to_f / lengths.size
end

#containers_with_defaultObject



64
65
66
67
68
# File 'lib/rack/mount/multimap.rb', line 64

def containers_with_default
  containers = []
  each_container_with_default { |container| containers << container }
  containers
end

#heightObject



55
56
57
# File 'lib/rack/mount/multimap.rb', line 55

def height
  containers_with_default.max { |a, b| a.length <=> b.length }.length
end

#initialize_copy(original) ⇒ Object



7
8
9
10
11
12
# File 'lib/rack/mount/multimap.rb', line 7

def initialize_copy(original)
  @hash = Hash.new(original.default.dup)
  original.hash.each_pair do |key, container|
    @hash[key] = container.dup
  end
end

#store(*args) ⇒ Object Also known as: []=

Raises:

  • (ArgumentError)


14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/rack/mount/multimap.rb', line 14

def store(*args)
  keys  = args.dup
  value = keys.pop
  key   = keys.shift

  raise ArgumentError, 'wrong number of arguments (1 for 2)' unless value

  unless key.respond_to?(:=~)
    raise ArgumentError, "unsupported key: #{args.first.inspect}"
  end

  if key.is_a?(Regexp)
    if keys.empty?
      @hash.each_pair { |k, l| l << value if k =~ key }
      self.default << value
    else
      @hash.each_pair { |k, _|
        if k =~ key
          args[0] = k
          _store(*args)
        end
      }

      self.default = self.class.new(default) unless default.is_a?(self.class)
      default[*keys.dup] = value
    end
  else
    _store(*args)
  end
end