Module: NestedArray::Nested

Extended by:
ActiveSupport::Concern
Included in:
Array, Array
Defined in:
lib/nested_array/nested.rb

Defined Under Namespace

Classes: Error

Instance Method Summary collapse

Instance Method Details

#concat_nested(tree = nil, options = {}) ⇒ Object

“Скеивание” вложенных структур ноды склеиваются если путь к ним одинаков; путь определяется из сложения Текстов (конфигурируемо через :path_key);



342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
# File 'lib/nested_array/nested.rb', line 342

def concat_nested tree=nil, options={}
  options = NESTED_OPTIONS.merge options
  return self if tree.nil?
  children_cache = {}
  tree.each_nested options do |node, parents, level|
    parent_path_names = parents.compact.map{|e| e[options[:path_key]]}
    parent_path = parent_path_names.join(options[:path_separator])
    path = parent_path_names.push(node[options[:path_key]]).join(options[:path_separator])
    element = node
    if !children_cache.keys.include? path
      if parent_path == ''
        array = self
      else
        array = children_cache[parent_path]
      end
      element[options[:children]] = []
      array << element
      children_cache[parent_path] = array
      children_cache[path] = element[options[:children]]
    end
  end
  self
end

#each_nested(options = {}) ⇒ Object

Перебирает вложенную стуктуру.



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/nested_array/nested.rb', line 44

def each_nested options={}
  options = NESTED_OPTIONS.merge options
  level = 0
  cache = []
  cache[level] = self.clone
  parents = []
  parents[level] = nil
  i = []
  i[level] = 0
  while level >= 0
    node = cache[level][i[level]]
    i[level]+= 1
    if node != nil
      is_last_children = cache[level][i[level]].blank?

      yield(node.clone, parents.clone, level, is_last_children, node.origin)

      if !node[options[:children]].nil? && node[options[:children]].length > 0
        level+= 1
        parents[level] = node.clone
        cache[level] = node[options[:children]]
        i[level] = 0
      end
    else
      parents[level] = nil
      level-= 1
    end
  end
  self
end

#each_nested!(options = {}) ⇒ Object



75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/nested_array/nested.rb', line 75

def each_nested! options={}
  options = NESTED_OPTIONS.merge options
  level = 0
  cache = []
  cache[level] = self
  parents = []
  parents[level] = nil
  i = []
  i[level] = 0
  while level >= 0
    node = cache[level][i[level]]
    i[level]+= 1
    if node != nil
      is_last_children = cache[level][i[level]].blank?

      yield(node, parents, level, is_last_children, node.origin)

      if !node[options[:children]].nil? && node[options[:children]].length > 0
        level+= 1
        parents[level] = node
        cache[level] = node[options[:children]]
        i[level] = 0
      end
    else
      parents[level] = nil
      level-= 1
    end
  end
  self
end

#nested_to_collection_select(options = {}) ⇒ Object

Преобразует вложенную структуру данных в плоскую, но добавляет в значение поля отвечающего за текстовое представление (:name) псевдографику древовидной структуры. Это позволяет вывести тэг select в сносном виде для использования с вложенными структурами.



321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
# File 'lib/nested_array/nested.rb', line 321

def nested_to_collection_select(options={})
  options = NESTED_OPTIONS.merge options
  ret = []
  last = []
  each_nested do |node, parents, level, is_last, origin|
    last[level+1] = is_last
    node_text = node[options[:option_text]]
    node_level = (1..level).map{|l| last[l] == true ? '&nbsp;' : ''}.join
    node_last = is_last ? '' : ''
    node_children = node[options[:children]].present? && node[options[:children]].length > 0 ? '' : ''
    option_text = "#{node_level}#{node_last}#{node_children}".html_safe + "#{node_text}"
    option_value = node[options[:option_value]]
    node[options[:option_text]] = option_text
    ret.push node
  end
  ret
end

#nested_to_html(options = {}) ⇒ Object



244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
# File 'lib/nested_array/nested.rb', line 244

def nested_to_html options={}
  options = NESTED_OPTIONS.merge options
  html = ''
  level = 0
  cache = []
  cache[level] = self.clone
  parents = []
  parents[level] = nil
  i = []
  i[level] = 0
  while level >= 0
    node = cache[level][i[level]]
    i[level]+= 1
    if node != nil

      node_html, node_options = yield(node.clone, parents.clone, level)
      html+= options[:tab] * (level * 2 + 1) if options[:tabulated]
      html+= node_options&.[](:li) || options[:li]
      html+= node_html.to_s

      if !node[options[:children]].nil? && node[options[:children]].length > 0
        level+= 1
        html+= "\n" if !options[:inline]
        html+= options[:tab] * (level * 2) if options[:tabulated]
        html+= node_options&.[](:ul) || options[:ul]
        html+= "\n" if !options[:inline]
        parents[level] = node.clone
        cache[level] = node[options[:children]]
        i[level] = 0
      else
        html+= options[:_li]
        html+= "\n" if !options[:inline]
      end
    else
      parents[level] = nil
      if level > 0
        html+= options[:tab] * (level * 2) if options[:tabulated]
        html+= options[:_ul]
        html+= "\n" if !options[:inline]
        html+= options[:tab] * (level * 2 - 1) if options[:tabulated]
        html+= options[:_li]
        html+= "\n" if !options[:inline]
      end
      level-= 1
    end
  end
  html.html_safe
end

#nested_to_options(options = {}) ⇒ Object

Возвращает массив для формирования опций html-тега <select> с псевдографикой, позволяющей вывести древовидную структуру. “‘

[‘option_text1’, ‘option_value1’],[‘option_text2’, ‘option_value2’],…

“‘



299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
# File 'lib/nested_array/nested.rb', line 299

def nested_to_options options={}
  options = NESTED_OPTIONS.merge options
  ret = []
  last = []
  each_nested do |node, parents, level, is_last|
    last[level+1] = is_last
    node_text = node[options[:option_text]]
    node_level = (1..level).map{|l| last[l] == true ? '&nbsp;' : ''}.join
    node_last = is_last ? '' : ''
    node_children = node[options[:children]].present? && node[options[:children]].length > 0 ? '' : ''
    option_text = "#{node_level}#{node_last}#{node_children}".html_safe + "#{node_text}"
    option_value = node[options[:option_value]]
    ret.push [option_text, option_value]
  end
  ret
end

#to_nested(options = {}) ⇒ Object



106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
# File 'lib/nested_array/nested.rb', line 106

def to_nested options={}
  options = NESTED_OPTIONS.merge options
  fields = {
    id: options[:id],
    parent_id: options[:parent_id],
    level: options[:level],
    children: options[:children],
  }
  fields.delete :level if !options[:add_level]
  cache = {}
  nested = options[:hashed] ? {} : []
  # Перебираем элементы в любом порядке!
  self.each do |value|
    origin = value
    value = value.serializable_hash if !value.is_a? Hash
    # 1. Если нет родителя текущего элемента, и текущий элемент не корневой, то:
    # 1.1 создадим родителя
    # 1.2 поместим в кэш
    if !(cache.key? value[fields[:parent_id]]) && (value[fields[:parent_id]] != options[:root_id])
      # 1.1
      temp = OpenStruct.new
      fields.each do |key, field|
        case key
        when :id
          temp[field] = value[fields[:parent_id]]
        when :children
          # не создаём поле
        else
          temp[field] = nil
        end
      end
      # 1.2
      cache[value[fields[:parent_id]]] = temp
    end
    # 2. Если текущий элемент уже был создан, значит он был чьим-то родителем, тогда:
    # 2.1 обновим в нем информацию
    # 2.2 поместим в родителя
    if cache.key? value[fields[:id]]
      # 2.1
      fields.each do |key, field|
        case key
        when :id, :children
          # не обновляем информацию
        else
          cache[value[fields[:id]]][field] = value[field]
        end
      end
      value.keys.each do |field|
        cache[value[fields[:id]]][field] = value[field] if !(field.in? fields)
      end
      cache[value[fields[:id]]].origin = origin
      # 2.2
      # Если текущий элемент не корневой - поместим в родителя, беря его из кэш
      if value[fields[:parent_id]] != options[:root_id]
        cache[value[fields[:parent_id]]][fields[:children]] ||= options[:hashed] ? {} : []
        if options[:hashed]
          cache[value[fields[:parent_id]]][fields[:children]][value[fields[:id]]] = nested[value[fields[:id]]]
        else
          cache[value[fields[:parent_id]]][fields[:children]] << cache[value[fields[:id]]]
        end
      # иначе, текущий элемент корневой, поместим в nested
      else
        if options[:hashed]
          nested[value[fields[:id]]] = cache[value[fields[:id]]]
        else
          nested << cache[value[fields[:id]]]
        end
      end
    # 3. Иначе, текущий элемент не создан, тогда:
    # 3.1 создадим элемент
    # 3.2 поместим в кэш
    # 3.3 поместим в родителя
    else
      # 3.1
      temp = OpenStruct.new
      fields.each do |key, field|
        case key
        when :id
          temp[field] = value[field]
        when :parent_id
          temp[field] = value[field]
        when :children
          # ничего не делаем
        else
          temp[field] = value[field]
        end
      end
      value.keys.each do |field|
        temp[field] = value[field] if !(field.in? fields)
      end
      temp.origin = origin
      # 3.2
      cache[value[fields[:id]]] = temp
      # 3.3
      # Если текущий элемент не корневой - поместим в родителя, беря его из кэш
      if value[fields[:parent_id]] != options[:root_id]
        cache[value[fields[:parent_id]]][fields[:children]] ||= options[:hashed] ? {} : []
        if options[:hashed]
          cache[value[fields[:parent_id]]][fields[:children]][value[fields[:id]]] = cache[value[fields[:id]]]
        else
          cache[value[fields[:parent_id]]][fields[:children]] << cache[value[fields[:id]]]
        end
      # иначе, текущий элемент корневой, поместим в nested
      else
        if options[:hashed]
          nested[value[fields[:id]]] = cache[value[fields[:id]]]
        else
          nested << cache[value[fields[:id]]]
        end
      end
    end
  end
  if options[:add_level]
    level = 0
    cache = []
    cache[level] = nested
    i = []
    i[level] = 0
    while level >= 0
      node = cache[level][i[level]]
      i[level]+= 1
      if node != nil

        node[options[:level]] = level

        if !node[options[:children]].nil? && node[options[:children]].length > 0
          level+= 1
          cache[level] = node[options[:children]]
          i[level] = 0
        end
      else
        level-= 1
      end
    end
  end
  nested
end