nested_array 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 880aa05be0fd0fb329899074ae93bfc0102ee21395f97659760b1edb4fbb0d13
4
+ data.tar.gz: 1f5c75337684947822f682a675d973e66da3ccda32d22940e5368e764d1366eb
5
+ SHA512:
6
+ metadata.gz: 18afc6985fef0c60904bed7bbc3f4b7415067b1cf40de01b14f94f63e165973e9029e3602c6fbdbba4af01229f7a45bcf6ac121a737e2e9aa3165807c198e137
7
+ data.tar.gz: 9ac78c96736adc41d8bee3ece6236c96f1bd65e47145e959a7aa1ac76f79461532acb7d4b75d72f755c54dcba1e70e7bbf5d2cf0b107d7387f339fa8150c2f87
data/.gitignore ADDED
@@ -0,0 +1,8 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
data/.ruby-version ADDED
@@ -0,0 +1 @@
1
+ 2.5.3
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source "https://rubygems.org"
2
+
3
+ # Specify your gem's dependencies in nested_array.gemspec
4
+ gemspec
data/Gemfile.lock ADDED
@@ -0,0 +1,20 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ nested_array (0.1.1)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ rake (10.5.0)
10
+
11
+ PLATFORMS
12
+ ruby
13
+
14
+ DEPENDENCIES
15
+ bundler (~> 2.0)
16
+ nested_array!
17
+ rake (~> 10.0)
18
+
19
+ BUNDLED WITH
20
+ 2.0.1
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2019 zlatov
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,39 @@
1
+ # NestedArray
2
+
3
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/nested_array`. To experiment with that code, run `bin/console` for an interactive prompt.
4
+
5
+ TODO: Delete this and the text above, and describe your gem
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'nested_array'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install nested_array
22
+
23
+ ## Usage
24
+
25
+ TODO: Write usage instructions here
26
+
27
+ ## Development
28
+
29
+ After checking out the repo, run `bin/setup` to install dependencies. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
30
+
31
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
32
+
33
+ ## Contributing
34
+
35
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/nested_array.
36
+
37
+ ## License
38
+
39
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,2 @@
1
+ require "bundler/gem_tasks"
2
+ task :default => :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "nested_array"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,308 @@
1
+ require "nested_array/version"
2
+
3
+ module NestedArray
4
+
5
+ class Error < StandardError
6
+ end
7
+
8
+ extend ActiveSupport::Concern
9
+
10
+ included do |recipient|
11
+
12
+ NESTED_OPTIONS = {
13
+ # Имена полей для получения/записи информации, чувствительны к string/symbol
14
+ id: :id,
15
+ parent_id: :pid,
16
+ children: :children,
17
+ level: :level,
18
+
19
+ # Параметры для преобразования в nested
20
+ hashed: false,
21
+ add_level: false,
22
+ root_id: nil,
23
+
24
+ # Параметры для преобразования в html
25
+ tabulated: true,
26
+ inline: false,
27
+ tab: "\t",
28
+ ul: '<ul>',
29
+ _ul: '</ul>',
30
+ li: '<li>',
31
+ _li: '</li>',
32
+
33
+ # Параматры для "склеивания" вложенных структур
34
+ path_separator: '-=path_separator=-',
35
+ path_key: 'text',
36
+ }
37
+ end
38
+
39
+ def each_nested options={}
40
+ options = NESTED_OPTIONS.merge options
41
+ level = 0
42
+ cache = []
43
+ cache[level] = self.clone
44
+ parents = []
45
+ parents[level] = nil
46
+ i = []
47
+ i[level] = 0
48
+ while level >= 0
49
+ node = cache[level][i[level]]
50
+ i[level]+= 1
51
+ if node != nil
52
+
53
+ yield(node.clone, parents.clone, level)
54
+
55
+ if !node[options[:children]].nil? && node[options[:children]].length > 0
56
+ level+= 1
57
+ parents[level] = node.clone
58
+ cache[level] = node[options[:children]]
59
+ i[level] = 0
60
+ end
61
+ else
62
+ parents[level] = nil
63
+ level-= 1
64
+ end
65
+ end
66
+ self
67
+ end
68
+
69
+ def each_nested! options={}
70
+ options = NESTED_OPTIONS.merge options
71
+ level = 0
72
+ cache = []
73
+ cache[level] = self
74
+ parents = []
75
+ parents[level] = nil
76
+ i = []
77
+ i[level] = 0
78
+ while level >= 0
79
+ node = cache[level][i[level]]
80
+ i[level]+= 1
81
+ if node != nil
82
+
83
+ yield(node, parents, level)
84
+
85
+ if !node[options[:children]].nil? && node[options[:children]].length > 0
86
+ level+= 1
87
+ parents[level] = node
88
+ cache[level] = node[options[:children]]
89
+ i[level] = 0
90
+ end
91
+ else
92
+ parents[level] = nil
93
+ level-= 1
94
+ end
95
+ end
96
+ self
97
+ end
98
+
99
+ def to_nested options={}
100
+ options = NESTED_OPTIONS.merge options
101
+ fields = {
102
+ id: options[:id],
103
+ parent_id: options[:parent_id],
104
+ level: options[:level],
105
+ children: options[:children],
106
+ }
107
+ fields.delete :level if !options[:add_level]
108
+ cache = {}
109
+ nested = options[:hashed] ? {} : []
110
+ # Перебираем элементы в любом порядке!
111
+ self.each do |value|
112
+ value = value.serializable_hash if !value.is_a? Hash
113
+ # 1. Если нет родителя текущего элемента, и текущий элемент не корневой, то:
114
+ # 1.1 создадим родителя
115
+ # 1.2 поместим в кэш
116
+ if !(cache.key? value[fields[:parent_id]]) && (value[fields[:parent_id]] != options[:root_id])
117
+ # 1.1
118
+ temp = {}
119
+ fields.each do |key, field|
120
+ case key
121
+ when :id
122
+ temp[field] = value[fields[:parent_id]]
123
+ when :children
124
+ # не создаём поле
125
+ else
126
+ temp[field] = nil
127
+ end
128
+ end
129
+ # 1.2
130
+ cache[value[fields[:parent_id]]] = temp
131
+ end
132
+ # 2. Если текущий элемент уже был создан, значит он был чьим-то родителем, тогда:
133
+ # 2.1 обновим в нем информацию
134
+ # 2.2 поместим в родителя
135
+ if cache.key? value[fields[:id]]
136
+ # 2.1
137
+ fields.each do |key, field|
138
+ case key
139
+ when :id, :children
140
+ # не обновляем информацию
141
+ else
142
+ cache[value[fields[:id]]][field] = value[field]
143
+ end
144
+ end
145
+ value.keys.each do |field|
146
+ cache[value[fields[:id]]][field] = value[field] if !(field.in? fields)
147
+ end
148
+ # 2.2
149
+ # Если текущий элемент не корневой - поместим в родителя, беря его из кэш
150
+ if value[fields[:parent_id]] != options[:root_id]
151
+ cache[value[fields[:parent_id]]][fields[:children]] ||= options[:hashed] ? {} : []
152
+ if options[:hashed]
153
+ cache[value[fields[:parent_id]]][fields[:children]][value[fields[:id]]] = nested[value[fields[:id]]]
154
+ else
155
+ cache[value[fields[:parent_id]]][fields[:children]] << cache[value[fields[:id]]]
156
+ end
157
+ # иначе, текущий элемент корневой, поместим в nested
158
+ else
159
+ if options[:hashed]
160
+ nested[value[fields[:id]]] = cache[value[fields[:id]]]
161
+ else
162
+ nested << cache[value[fields[:id]]]
163
+ end
164
+ end
165
+ # 3. Иначе, текущий элемент не создан, тогда:
166
+ # 3.1 создадим элемент
167
+ # 3.2 поместим в кэш
168
+ # 3.3 поместим в родителя
169
+ else
170
+ # 3.1
171
+ temp = {}
172
+ fields.each do |key, field|
173
+ case key
174
+ when :id
175
+ temp[field] = value[field]
176
+ when :parent_id
177
+ temp[field] = value[field]
178
+ when :children
179
+ # ничего не делаем
180
+ else
181
+ temp[field] = value[field]
182
+ end
183
+ end
184
+ value.keys.each do |field|
185
+ temp[field] = value[field] if !(field.in? fields)
186
+ end
187
+ # 3.2
188
+ cache[value[fields[:id]]] = temp
189
+ # 3.3
190
+ # Если текущий элемент не корневой - поместим в родителя, беря его из кэш
191
+ if value[fields[:parent_id]] != options[:root_id]
192
+ cache[value[fields[:parent_id]]][fields[:children]] ||= options[:hashed] ? {} : []
193
+ if options[:hashed]
194
+ cache[value[fields[:parent_id]]][fields[:children]][value[fields[:id]]] = cache[value[fields[:id]]]
195
+ else
196
+ cache[value[fields[:parent_id]]][fields[:children]] << cache[value[fields[:id]]]
197
+ end
198
+ # иначе, текущий элемент корневой, поместим в nested
199
+ else
200
+ if options[:hashed]
201
+ nested[value[fields[:id]]] = cache[value[fields[:id]]]
202
+ else
203
+ nested << cache[value[fields[:id]]]
204
+ end
205
+ end
206
+ end
207
+ end
208
+ if options[:add_level]
209
+ level = 0
210
+ cache = []
211
+ cache[level] = nested
212
+ i = []
213
+ i[level] = 0
214
+ while level >= 0
215
+ node = cache[level][i[level]]
216
+ i[level]+= 1
217
+ if node != nil
218
+
219
+ node[options[:level]] = level
220
+
221
+ if !node[options[:children]].nil? && node[options[:children]].length > 0
222
+ level+= 1
223
+ cache[level] = node[options[:children]]
224
+ i[level] = 0
225
+ end
226
+ else
227
+ level-= 1
228
+ end
229
+ end
230
+ end
231
+ nested
232
+ end
233
+
234
+ def nested_to_html options={}
235
+ options = NESTED_OPTIONS.merge options
236
+ html = ''
237
+ level = 0
238
+ cache = []
239
+ cache[level] = self.clone
240
+ parents = []
241
+ parents[level] = nil
242
+ i = []
243
+ i[level] = 0
244
+ while level >= 0
245
+ node = cache[level][i[level]]
246
+ i[level]+= 1
247
+ if node != nil
248
+
249
+ html+= options[:tab] * (level * 2 + 1) if options[:tabulated]
250
+ html+= options[:li]
251
+ html+= yield(node.clone, parents.clone, level)
252
+
253
+ if !node[:children].nil? && node[:children].length > 0
254
+ level+= 1
255
+ html+= "\n" if !options[:inline]
256
+ html+= options[:tab] * (level * 2) if options[:tabulated]
257
+ html+= options[:ul]
258
+ html+= "\n" if !options[:inline]
259
+ parents[level] = node.clone
260
+ cache[level] = node[:children]
261
+ i[level] = 0
262
+ else
263
+ html+= options[:_li]
264
+ html+= "\n" if !options[:inline]
265
+ end
266
+ else
267
+ parents[level] = nil
268
+ if level > 0
269
+ html+= options[:tab] * (level * 2) if options[:tabulated]
270
+ html+= options[:_ul]
271
+ html+= "\n" if !options[:inline]
272
+ html+= options[:tab] * (level * 2 - 1) if options[:tabulated]
273
+ html+= options[:_li]
274
+ html+= "\n" if !options[:inline]
275
+ end
276
+ level-= 1
277
+ end
278
+ end
279
+ html
280
+ end
281
+
282
+ # "Скеивание" вложенных структур
283
+ # ноды склеиваются если путь к ним одинаков;
284
+ # путь определяется из сложения Текстов (конфигурируемо через :path_key);
285
+ def concat_nested tree=nil, options={}
286
+ options = NESTED_OPTIONS.merge options
287
+ return self if tree.nil?
288
+ children_cache = {}
289
+ tree.each_nested options do |node, parents, level|
290
+ parent_path_names = parents.compact.map{|e| e[options[:path_key]]}
291
+ parent_path = parent_path_names.join(options[:path_separator])
292
+ path = parent_path_names.push(node[options[:path_key]]).join(options[:path_separator])
293
+ element = node
294
+ if !children_cache.keys.include? path
295
+ if parent_path == ''
296
+ array = self
297
+ else
298
+ array = children_cache[parent_path]
299
+ end
300
+ element[options[:children]] = []
301
+ array << element
302
+ children_cache[parent_path] = array
303
+ children_cache[path] = element[options[:children]]
304
+ end
305
+ end
306
+ self
307
+ end
308
+ end
@@ -0,0 +1,3 @@
1
+ module NestedArray
2
+ VERSION = "0.1.2"
3
+ end
@@ -0,0 +1,41 @@
1
+
2
+ lib = File.expand_path("../lib", __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require "nested_array/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "nested_array"
8
+ spec.version = NestedArray::VERSION
9
+ spec.authors = ["zlatov"]
10
+ spec.email = ["zlatov@ya.ru"]
11
+
12
+ spec.summary = "Convert a flat array into a nested one in 1 pass and another…"
13
+ # spec.description = %q{TODO: Write a longer description or delete this line.}
14
+ spec.homepage = "https://github.com/Zlatov/nested_array"
15
+ spec.license = "MIT"
16
+
17
+ # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
18
+ # to allow pushing to a single host or delete this section to allow pushing to any host.
19
+ if spec.respond_to?(:metadata)
20
+ # spec.metadata["allowed_push_host"] = "https://rubygems.org"
21
+
22
+ spec.metadata["homepage_uri"] = spec.homepage
23
+ spec.metadata["source_code_uri"] = "https://github.com/Zlatov/nested_array.git"
24
+ # spec.metadata["changelog_uri"] = "TODO: Put your gem's CHANGELOG.md URL here."
25
+ else
26
+ raise "RubyGems 2.0 or newer is required to protect against " \
27
+ "public gem pushes."
28
+ end
29
+
30
+ # Specify which files should be added to the gem when it is released.
31
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
32
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
33
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
34
+ end
35
+ spec.bindir = "exe"
36
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
37
+ spec.require_paths = ["lib"]
38
+
39
+ spec.add_development_dependency "bundler", "~> 2.0"
40
+ spec.add_development_dependency "rake", "~> 10.0"
41
+ end
metadata ADDED
@@ -0,0 +1,85 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: nested_array
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.2
5
+ platform: ruby
6
+ authors:
7
+ - zlatov
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2019-10-25 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '2.0'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '2.0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ description:
42
+ email:
43
+ - zlatov@ya.ru
44
+ executables: []
45
+ extensions: []
46
+ extra_rdoc_files: []
47
+ files:
48
+ - ".gitignore"
49
+ - ".ruby-version"
50
+ - Gemfile
51
+ - Gemfile.lock
52
+ - LICENSE.txt
53
+ - README.md
54
+ - Rakefile
55
+ - bin/console
56
+ - bin/setup
57
+ - lib/nested_array.rb
58
+ - lib/nested_array/version.rb
59
+ - nested_array.gemspec
60
+ homepage: https://github.com/Zlatov/nested_array
61
+ licenses:
62
+ - MIT
63
+ metadata:
64
+ homepage_uri: https://github.com/Zlatov/nested_array
65
+ source_code_uri: https://github.com/Zlatov/nested_array.git
66
+ post_install_message:
67
+ rdoc_options: []
68
+ require_paths:
69
+ - lib
70
+ required_ruby_version: !ruby/object:Gem::Requirement
71
+ requirements:
72
+ - - ">="
73
+ - !ruby/object:Gem::Version
74
+ version: '0'
75
+ required_rubygems_version: !ruby/object:Gem::Requirement
76
+ requirements:
77
+ - - ">="
78
+ - !ruby/object:Gem::Version
79
+ version: '0'
80
+ requirements: []
81
+ rubygems_version: 3.0.3
82
+ signing_key:
83
+ specification_version: 4
84
+ summary: Convert a flat array into a nested one in 1 pass and another…
85
+ test_files: []