Class: Rack::Mount::NestedSet

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

Overview

:nodoc:

Defined Under Namespace

Classes: List

Constant Summary collapse

WILD_REGEXP =
/.*/.freeze

Instance Method Summary collapse

Constructor Details

#initialize(default = List.new) ⇒ NestedSet

Returns a new instance of NestedSet.



11
12
13
# File 'lib/rack/mount/nested_set.rb', line 11

def initialize(default = List.new)
  super(default)
end

Instance Method Details

#<<(value) ⇒ Object



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

def <<(value)
  values_with_default.each { |e| e << value }
  nil
end

#[](*keys) ⇒ Object



55
56
57
58
59
60
61
62
# File 'lib/rack/mount/nested_set.rb', line 55

def [](*keys)
  result, i = self, 0
  until result.is_a?(Array)
    result = result.at(keys[i])
    i += 1
  end
  result
end

#[]=(*args) ⇒ Object

Raises:

  • (ArgumentError)


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
44
45
46
47
48
49
50
51
52
53
# File 'lib/rack/mount/nested_set.rb', line 19

def []=(*args)
  args  = args.flatten
  value = args.pop
  key   = args.shift.freeze
  key   = WILD_REGEXP if key.nil?
  keys  = args.freeze

  raise ArgumentError, 'missing value' unless value

  case key
  when Regexp
    if keys.empty?
      each { |k, v| v << value if key =~ k }
      default << value
    else
      each { |k, v| v[keys.dup] = value if key =~ k }
      self.default = NestedSet.new(default) if default.is_a?(List)
      default[keys.dup] = value
    end
  when String
    v = at(key)
    v = v.dup if v.equal?(default)

    if keys.empty?
      v << value
    else
      v = NestedSet.new(v) if v.is_a?(List)
      v[keys.dup] = value
    end

    super(key, v)
  else
    raise ArgumentError, 'unsupported key'
  end
end

#atObject



15
# File 'lib/rack/mount/nested_set.rb', line 15

alias_method :at, :[]

#freezeObject



77
78
79
80
# File 'lib/rack/mount/nested_set.rb', line 77

def freeze
  values_with_default.each { |v| v.freeze }
  super
end

#heightObject



96
97
98
# File 'lib/rack/mount/nested_set.rb', line 96

def height
  longest_list_descendant.length
end

#inspectObject



73
74
75
# File 'lib/rack/mount/nested_set.rb', line 73

def inspect
  super.gsub(/\}$/, ", nil => #{default.inspect}}")
end

#listsObject



82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/rack/mount/nested_set.rb', line 82

def lists
  descendants = []
  values_with_default.each do |v|
    if v.is_a?(NestedSet)
      v.lists.each do |descendant|
        descendants << descendant
      end
    else
      descendants << v
    end
  end
  descendants
end

#values_with_defaultObject



69
70
71
# File 'lib/rack/mount/nested_set.rb', line 69

def values_with_default
  values.push(default)
end