nested_array 1.0.0 → 1.1.0
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 +4 -4
- data/Gemfile +2 -0
- data/Gemfile.lock +14 -1
- data/README-ru.md +151 -0
- data/README.md +27 -11
- data/bash/push/gem.sh +15 -0
- data/bash/test/gem.sh +2 -2
- data/bin/bundle +105 -0
- data/bin/byebug +29 -0
- data/bin/htmldiff +29 -0
- data/bin/ldiff +29 -0
- data/bin/rake +29 -0
- data/bin/rspec +29 -0
- data/dev/nested_options.rb +25 -0
- data/lib/nested_array/nested.rb +40 -9
- data/lib/nested_array/version.rb +1 -1
- data/lib/nested_array.rb +5 -0
- metadata +11 -3
- data/lib/.byebug_history +0 -10
checksums.yaml
CHANGED
@@ -1,7 +1,7 @@
|
|
1
1
|
---
|
2
2
|
SHA256:
|
3
|
-
metadata.gz:
|
4
|
-
data.tar.gz:
|
3
|
+
metadata.gz: 1226eabba471ff36c05d62793baa80196a9b5126182f43f0e8c17a1d381bbed0
|
4
|
+
data.tar.gz: 904e12afa79e89cde37afad62e1fb3d71896927d21da1ee8e4232009d253200e
|
5
5
|
SHA512:
|
6
|
-
metadata.gz:
|
7
|
-
data.tar.gz:
|
6
|
+
metadata.gz: cd090bbf6513c6423df792a2bc1f9408e6dbc13d29e7ea1314320d87c6209585ba78c51144346f7a508e3db69abedc36bd9c043554cc1c49bdd22569ead700e3
|
7
|
+
data.tar.gz: 59c94c994b131ef551e2f36c3dfde6a3442522a6dd9260c66d44fd78f9bf81e833113513319b64e81858f24ed0e59b000f54828eb2fc29c8d557a50055e4a08b
|
data/Gemfile
CHANGED
data/Gemfile.lock
CHANGED
@@ -1,14 +1,23 @@
|
|
1
1
|
PATH
|
2
2
|
remote: .
|
3
3
|
specs:
|
4
|
-
nested_array (1.0.
|
4
|
+
nested_array (1.0.1)
|
5
5
|
|
6
6
|
GEM
|
7
7
|
remote: https://rubygems.org/
|
8
8
|
specs:
|
9
|
+
activesupport (5.2.4.1)
|
10
|
+
concurrent-ruby (~> 1.0, >= 1.0.2)
|
11
|
+
i18n (>= 0.7, < 2)
|
12
|
+
minitest (~> 5.1)
|
13
|
+
tzinfo (~> 1.1)
|
9
14
|
awesome_print (1.8.0)
|
10
15
|
byebug (11.0.1)
|
16
|
+
concurrent-ruby (1.1.5)
|
11
17
|
diff-lcs (1.3)
|
18
|
+
i18n (1.7.0)
|
19
|
+
concurrent-ruby (~> 1.0)
|
20
|
+
minitest (5.13.0)
|
12
21
|
rake (10.5.0)
|
13
22
|
rspec (3.9.0)
|
14
23
|
rspec-core (~> 3.9.0)
|
@@ -23,11 +32,15 @@ GEM
|
|
23
32
|
diff-lcs (>= 1.2.0, < 2.0)
|
24
33
|
rspec-support (~> 3.9.0)
|
25
34
|
rspec-support (3.9.0)
|
35
|
+
thread_safe (0.3.6)
|
36
|
+
tzinfo (1.2.6)
|
37
|
+
thread_safe (~> 0.1)
|
26
38
|
|
27
39
|
PLATFORMS
|
28
40
|
ruby
|
29
41
|
|
30
42
|
DEPENDENCIES
|
43
|
+
activesupport (~> 5.0, >= 5.0.0.1)
|
31
44
|
awesome_print (~> 1.8)
|
32
45
|
bundler (~> 2.0)
|
33
46
|
byebug (~> 11.0)
|
data/README-ru.md
ADDED
@@ -0,0 +1,151 @@
|
|
1
|
+
# NestedArray
|
2
|
+
|
3
|
+
Предназначен для преобразования в древовидную структуру плоских данных описанных по паттерну «Список смежности» (Adjacency List), то есть в нодах указа предок `parent_id`. Например:
|
4
|
+
|
5
|
+
```ruby
|
6
|
+
[
|
7
|
+
{id: 1, parent_id: nil, name: 'first', …},
|
8
|
+
{id: 2, parent_id: 1, name: 'second', …},
|
9
|
+
{id: 3, parent_id: 1, name: 'third', …}
|
10
|
+
]
|
11
|
+
# ↓ ↓ ↓
|
12
|
+
[
|
13
|
+
{id: 1, parent_id: nil, name: 'first', children: [
|
14
|
+
{id: 2, parent_id: 1, name: 'second', …},
|
15
|
+
{id: 3, parent_id: 1, name: 'third', …}
|
16
|
+
], …}
|
17
|
+
]
|
18
|
+
```
|
19
|
+
|
20
|
+
|
21
|
+
## Установка
|
22
|
+
|
23
|
+
Добавте строку в _Gemfile_ вашего приложения:
|
24
|
+
|
25
|
+
```ruby
|
26
|
+
gem 'nested_array', '~> 1.1.0'
|
27
|
+
```
|
28
|
+
|
29
|
+
И затем выполните `bundle install`.
|
30
|
+
|
31
|
+
Или установите его как `gem install nested_array`
|
32
|
+
|
33
|
+
|
34
|
+
## Использование
|
35
|
+
|
36
|
+
__Список методов__
|
37
|
+
|
38
|
+
* `to_nested` — преобразует плоскую структуро во вложенную;
|
39
|
+
* `each_nested` — перебирает вложенную стуктуру;
|
40
|
+
* `each_nested!` — перебирает вложенную стуктуру, предоставляя доступ к исходным данным;
|
41
|
+
* `nested_to_html` — преобразует вложенную структуру в html вёрстку (многоуровневый список `<ul><li>…`);
|
42
|
+
* `nested_to_options` — преобразует вложенную в массив для формирования опций html-тега `<select>` с псевдографикой;
|
43
|
+
* `concat_nested` — скеивание вложенных структур, ноды склеиваются если путь к ним одинаков.
|
44
|
+
|
45
|
+
### to_nested
|
46
|
+
|
47
|
+
Преобразует плоскую структуро во вложенную.
|
48
|
+
|
49
|
+
```ruby
|
50
|
+
a = [{'id' => 1, 'parent_id' => nil}]
|
51
|
+
a = NestedArray::Array.new
|
52
|
+
b = a.to_nested
|
53
|
+
```
|
54
|
+
|
55
|
+
__Опции__
|
56
|
+
|
57
|
+
У каждой ноды вложенной структуры есть базовые свойства, такие как идентификатор, идентификатор предка и другие. Для доступа к этим данным используются ключи, которые можно настроить как в примере ниже. По умолчанию используются следующие __строковые__ (_чувствительны к string/symbol_) ключи:
|
58
|
+
|
59
|
+
```ruby
|
60
|
+
b = a.to_nested({
|
61
|
+
id: 'id', # указывает какое свойство ноды является идентификатором;
|
62
|
+
parent_id: 'parent_id', # -//- предком;
|
63
|
+
children: 'children', # -//- массивом потомков;
|
64
|
+
level: 'level' # -//- дополнительным свойством с уровнем вложенности;
|
65
|
+
root_id: nil # определяет что является корнем для построения дерева,
|
66
|
+
# например, для построения ветви корнем корнем
|
67
|
+
# является идентификатор одной из нод.
|
68
|
+
})
|
69
|
+
```
|
70
|
+
|
71
|
+
Дополнительные опции преобразования:
|
72
|
+
|
73
|
+
```ruby
|
74
|
+
b = a.to_nested({
|
75
|
+
hashed: false, # потомки могут храниться не в массиве а в хэше;
|
76
|
+
add_level: false, # добавляет в ноду информацию о уровене вложенности ноды;
|
77
|
+
})
|
78
|
+
```
|
79
|
+
|
80
|
+
### each_nested
|
81
|
+
|
82
|
+
Перебирает вложенную стуктуру.
|
83
|
+
|
84
|
+
```ruby
|
85
|
+
nested.each_nested do |node, parents, level, is_last_children|
|
86
|
+
puts node # > {'id' => ...}
|
87
|
+
puts parents # > [{'id' => ...}]
|
88
|
+
puts level # > 0
|
89
|
+
puts is_last_children # > false
|
90
|
+
end
|
91
|
+
```
|
92
|
+
|
93
|
+
### nested_to_html
|
94
|
+
|
95
|
+
__Опции__
|
96
|
+
|
97
|
+
```ruby
|
98
|
+
tabulated: true,
|
99
|
+
inline: false,
|
100
|
+
tab: "\t",
|
101
|
+
ul: '<ul>',
|
102
|
+
_ul: '</ul>',
|
103
|
+
li: '<li>',
|
104
|
+
_li: '</li>',
|
105
|
+
```
|
106
|
+
|
107
|
+
### nested_to_options
|
108
|
+
|
109
|
+
Формирования опций для html-тега <select>
|
110
|
+
|
111
|
+
Возвращает массив с псевдографикой, позволяющей вывести древовидную структуру.
|
112
|
+
|
113
|
+
```ruby
|
114
|
+
|
115
|
+
[['option_text1', 'option_value1'],['option_text2', 'option_value2'],…]
|
116
|
+
```
|
117
|
+
|
118
|
+
__Опции__
|
119
|
+
|
120
|
+
```ruby
|
121
|
+
option_value: 'id', # Что брать в качестве значений при формировании опций селекта.
|
122
|
+
option_text: 'name',
|
123
|
+
```
|
124
|
+
|
125
|
+
### concat_nested
|
126
|
+
|
127
|
+
Скеивание вложенных структур.
|
128
|
+
|
129
|
+
* Ноды склеиваются если путь к ним одинаков;
|
130
|
+
* Путь определяется из сложения Текстов (конфигурируемо через :path_key);
|
131
|
+
|
132
|
+
__Опции__
|
133
|
+
|
134
|
+
```ruby
|
135
|
+
path_separator: '-=path_separator=-',
|
136
|
+
path_key: 'text',
|
137
|
+
```
|
138
|
+
|
139
|
+
## Development
|
140
|
+
|
141
|
+
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.
|
142
|
+
|
143
|
+
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).
|
144
|
+
|
145
|
+
## Contributing
|
146
|
+
|
147
|
+
Bug reports and pull requests are welcome on GitHub at https://github.com/Zlatov/nested_array.
|
148
|
+
|
149
|
+
## License
|
150
|
+
|
151
|
+
The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
|
data/README.md
CHANGED
@@ -1,28 +1,44 @@
|
|
1
1
|
# NestedArray
|
2
2
|
|
3
|
-
|
3
|
+
It is intended for transformation into a tree structure of flat data described by the “Adjacency List” pattern, that is, the ancestor is specified in the nodes by the field `parent_id`. For instance:
|
4
|
+
|
5
|
+
```ruby
|
6
|
+
[
|
7
|
+
{id: 1, parent_id: nil, name: 'first', …},
|
8
|
+
{id: 2, parent_id: 1, name: 'second', …},
|
9
|
+
{id: 3, parent_id: 1, name: 'third', …}
|
10
|
+
]
|
11
|
+
# ↓ ↓ ↓
|
12
|
+
[
|
13
|
+
{id: 1, parent_id: nil, name: 'first', children: [
|
14
|
+
{id: 2, parent_id: 1, name: 'second', …},
|
15
|
+
{id: 3, parent_id: 1, name: 'third', …}
|
16
|
+
], …}
|
17
|
+
]
|
18
|
+
```
|
4
19
|
|
5
|
-
TODO: Delete this and the text above, and describe your gem
|
6
20
|
|
7
21
|
## Installation
|
8
22
|
|
9
23
|
Add this line to your application's Gemfile:
|
10
24
|
|
11
25
|
```ruby
|
12
|
-
gem 'nested_array'
|
26
|
+
gem 'nested_array', '~> 1.0.0'
|
13
27
|
```
|
14
28
|
|
15
|
-
And then execute:
|
29
|
+
And then execute: `bundle`.
|
16
30
|
|
17
|
-
|
18
|
-
|
19
|
-
Or install it yourself as:
|
20
|
-
|
21
|
-
$ gem install nested_array
|
31
|
+
Or install it yourself as `gem install nested_array`.
|
22
32
|
|
23
33
|
## Usage
|
24
34
|
|
25
|
-
|
35
|
+
```html
|
36
|
+
<ul>
|
37
|
+
<%= Catalogs.all.to_a.to_nested.nested_to_html do |node| %>
|
38
|
+
<% link_to "#{node['name']}", catalog_view_path(node['slug']) %>
|
39
|
+
<% end %>
|
40
|
+
</ul>
|
41
|
+
```
|
26
42
|
|
27
43
|
## Development
|
28
44
|
|
@@ -32,7 +48,7 @@ To install this gem onto your local machine, run `bundle exec rake install`. To
|
|
32
48
|
|
33
49
|
## Contributing
|
34
50
|
|
35
|
-
Bug reports and pull requests are welcome on GitHub at https://github.com/
|
51
|
+
Bug reports and pull requests are welcome on GitHub at https://github.com/Zlatov/nested_array.
|
36
52
|
|
37
53
|
## License
|
38
54
|
|
data/bash/push/gem.sh
ADDED
data/bash/test/gem.sh
CHANGED
@@ -7,5 +7,5 @@ cd "$(dirname "${0}")"
|
|
7
7
|
cd ../..
|
8
8
|
|
9
9
|
# rspec управляет загружаемыми гемами, поэтому сам rspec запускается НЕ `bundle exec rspec`, а просто `rspec`
|
10
|
-
rspec --format doc ./spec/array_spec.rb
|
11
|
-
rspec --format doc ./spec/nested_array_array_spec.rb
|
10
|
+
./bin/rspec --format doc ./spec/array_spec.rb
|
11
|
+
./bin/rspec --format doc ./spec/nested_array_array_spec.rb
|
data/bin/bundle
ADDED
@@ -0,0 +1,105 @@
|
|
1
|
+
#!/usr/bin/env ruby
|
2
|
+
# frozen_string_literal: true
|
3
|
+
|
4
|
+
#
|
5
|
+
# This file was generated by Bundler.
|
6
|
+
#
|
7
|
+
# The application 'bundle' is installed as part of a gem, and
|
8
|
+
# this file is here to facilitate running it.
|
9
|
+
#
|
10
|
+
|
11
|
+
require "rubygems"
|
12
|
+
|
13
|
+
m = Module.new do
|
14
|
+
module_function
|
15
|
+
|
16
|
+
def invoked_as_script?
|
17
|
+
File.expand_path($0) == File.expand_path(__FILE__)
|
18
|
+
end
|
19
|
+
|
20
|
+
def env_var_version
|
21
|
+
ENV["BUNDLER_VERSION"]
|
22
|
+
end
|
23
|
+
|
24
|
+
def cli_arg_version
|
25
|
+
return unless invoked_as_script? # don't want to hijack other binstubs
|
26
|
+
return unless "update".start_with?(ARGV.first || " ") # must be running `bundle update`
|
27
|
+
bundler_version = nil
|
28
|
+
update_index = nil
|
29
|
+
ARGV.each_with_index do |a, i|
|
30
|
+
if update_index && update_index.succ == i && a =~ Gem::Version::ANCHORED_VERSION_PATTERN
|
31
|
+
bundler_version = a
|
32
|
+
end
|
33
|
+
next unless a =~ /\A--bundler(?:[= ](#{Gem::Version::VERSION_PATTERN}))?\z/
|
34
|
+
bundler_version = $1 || ">= 0.a"
|
35
|
+
update_index = i
|
36
|
+
end
|
37
|
+
bundler_version
|
38
|
+
end
|
39
|
+
|
40
|
+
def gemfile
|
41
|
+
gemfile = ENV["BUNDLE_GEMFILE"]
|
42
|
+
return gemfile if gemfile && !gemfile.empty?
|
43
|
+
|
44
|
+
File.expand_path("../../Gemfile", __FILE__)
|
45
|
+
end
|
46
|
+
|
47
|
+
def lockfile
|
48
|
+
lockfile =
|
49
|
+
case File.basename(gemfile)
|
50
|
+
when "gems.rb" then gemfile.sub(/\.rb$/, gemfile)
|
51
|
+
else "#{gemfile}.lock"
|
52
|
+
end
|
53
|
+
File.expand_path(lockfile)
|
54
|
+
end
|
55
|
+
|
56
|
+
def lockfile_version
|
57
|
+
return unless File.file?(lockfile)
|
58
|
+
lockfile_contents = File.read(lockfile)
|
59
|
+
return unless lockfile_contents =~ /\n\nBUNDLED WITH\n\s{2,}(#{Gem::Version::VERSION_PATTERN})\n/
|
60
|
+
Regexp.last_match(1)
|
61
|
+
end
|
62
|
+
|
63
|
+
def bundler_version
|
64
|
+
@bundler_version ||= begin
|
65
|
+
env_var_version || cli_arg_version ||
|
66
|
+
lockfile_version || "#{Gem::Requirement.default}.a"
|
67
|
+
end
|
68
|
+
end
|
69
|
+
|
70
|
+
def load_bundler!
|
71
|
+
ENV["BUNDLE_GEMFILE"] ||= gemfile
|
72
|
+
|
73
|
+
# must dup string for RG < 1.8 compatibility
|
74
|
+
activate_bundler(bundler_version.dup)
|
75
|
+
end
|
76
|
+
|
77
|
+
def activate_bundler(bundler_version)
|
78
|
+
if Gem::Version.correct?(bundler_version) && Gem::Version.new(bundler_version).release < Gem::Version.new("2.0")
|
79
|
+
bundler_version = "< 2"
|
80
|
+
end
|
81
|
+
gem_error = activation_error_handling do
|
82
|
+
gem "bundler", bundler_version
|
83
|
+
end
|
84
|
+
return if gem_error.nil?
|
85
|
+
require_error = activation_error_handling do
|
86
|
+
require "bundler/version"
|
87
|
+
end
|
88
|
+
return if require_error.nil? && Gem::Requirement.new(bundler_version).satisfied_by?(Gem::Version.new(Bundler::VERSION))
|
89
|
+
warn "Activating bundler (#{bundler_version}) failed:\n#{gem_error.message}\n\nTo install the version of bundler this project requires, run `gem install bundler -v '#{bundler_version}'`"
|
90
|
+
exit 42
|
91
|
+
end
|
92
|
+
|
93
|
+
def activation_error_handling
|
94
|
+
yield
|
95
|
+
nil
|
96
|
+
rescue StandardError, LoadError => e
|
97
|
+
e
|
98
|
+
end
|
99
|
+
end
|
100
|
+
|
101
|
+
m.load_bundler!
|
102
|
+
|
103
|
+
if m.invoked_as_script?
|
104
|
+
load Gem.bin_path("bundler", "bundle")
|
105
|
+
end
|
data/bin/byebug
ADDED
@@ -0,0 +1,29 @@
|
|
1
|
+
#!/usr/bin/env ruby
|
2
|
+
# frozen_string_literal: true
|
3
|
+
|
4
|
+
#
|
5
|
+
# This file was generated by Bundler.
|
6
|
+
#
|
7
|
+
# The application 'byebug' is installed as part of a gem, and
|
8
|
+
# this file is here to facilitate running it.
|
9
|
+
#
|
10
|
+
|
11
|
+
require "pathname"
|
12
|
+
ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile",
|
13
|
+
Pathname.new(__FILE__).realpath)
|
14
|
+
|
15
|
+
bundle_binstub = File.expand_path("../bundle", __FILE__)
|
16
|
+
|
17
|
+
if File.file?(bundle_binstub)
|
18
|
+
if File.read(bundle_binstub, 300) =~ /This file was generated by Bundler/
|
19
|
+
load(bundle_binstub)
|
20
|
+
else
|
21
|
+
abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run.
|
22
|
+
Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.")
|
23
|
+
end
|
24
|
+
end
|
25
|
+
|
26
|
+
require "rubygems"
|
27
|
+
require "bundler/setup"
|
28
|
+
|
29
|
+
load Gem.bin_path("byebug", "byebug")
|
data/bin/htmldiff
ADDED
@@ -0,0 +1,29 @@
|
|
1
|
+
#!/usr/bin/env ruby
|
2
|
+
# frozen_string_literal: true
|
3
|
+
|
4
|
+
#
|
5
|
+
# This file was generated by Bundler.
|
6
|
+
#
|
7
|
+
# The application 'htmldiff' is installed as part of a gem, and
|
8
|
+
# this file is here to facilitate running it.
|
9
|
+
#
|
10
|
+
|
11
|
+
require "pathname"
|
12
|
+
ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile",
|
13
|
+
Pathname.new(__FILE__).realpath)
|
14
|
+
|
15
|
+
bundle_binstub = File.expand_path("../bundle", __FILE__)
|
16
|
+
|
17
|
+
if File.file?(bundle_binstub)
|
18
|
+
if File.read(bundle_binstub, 300) =~ /This file was generated by Bundler/
|
19
|
+
load(bundle_binstub)
|
20
|
+
else
|
21
|
+
abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run.
|
22
|
+
Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.")
|
23
|
+
end
|
24
|
+
end
|
25
|
+
|
26
|
+
require "rubygems"
|
27
|
+
require "bundler/setup"
|
28
|
+
|
29
|
+
load Gem.bin_path("diff-lcs", "htmldiff")
|
data/bin/ldiff
ADDED
@@ -0,0 +1,29 @@
|
|
1
|
+
#!/usr/bin/env ruby
|
2
|
+
# frozen_string_literal: true
|
3
|
+
|
4
|
+
#
|
5
|
+
# This file was generated by Bundler.
|
6
|
+
#
|
7
|
+
# The application 'ldiff' is installed as part of a gem, and
|
8
|
+
# this file is here to facilitate running it.
|
9
|
+
#
|
10
|
+
|
11
|
+
require "pathname"
|
12
|
+
ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile",
|
13
|
+
Pathname.new(__FILE__).realpath)
|
14
|
+
|
15
|
+
bundle_binstub = File.expand_path("../bundle", __FILE__)
|
16
|
+
|
17
|
+
if File.file?(bundle_binstub)
|
18
|
+
if File.read(bundle_binstub, 300) =~ /This file was generated by Bundler/
|
19
|
+
load(bundle_binstub)
|
20
|
+
else
|
21
|
+
abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run.
|
22
|
+
Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.")
|
23
|
+
end
|
24
|
+
end
|
25
|
+
|
26
|
+
require "rubygems"
|
27
|
+
require "bundler/setup"
|
28
|
+
|
29
|
+
load Gem.bin_path("diff-lcs", "ldiff")
|
data/bin/rake
ADDED
@@ -0,0 +1,29 @@
|
|
1
|
+
#!/usr/bin/env ruby
|
2
|
+
# frozen_string_literal: true
|
3
|
+
|
4
|
+
#
|
5
|
+
# This file was generated by Bundler.
|
6
|
+
#
|
7
|
+
# The application 'rake' is installed as part of a gem, and
|
8
|
+
# this file is here to facilitate running it.
|
9
|
+
#
|
10
|
+
|
11
|
+
require "pathname"
|
12
|
+
ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile",
|
13
|
+
Pathname.new(__FILE__).realpath)
|
14
|
+
|
15
|
+
bundle_binstub = File.expand_path("../bundle", __FILE__)
|
16
|
+
|
17
|
+
if File.file?(bundle_binstub)
|
18
|
+
if File.read(bundle_binstub, 300) =~ /This file was generated by Bundler/
|
19
|
+
load(bundle_binstub)
|
20
|
+
else
|
21
|
+
abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run.
|
22
|
+
Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.")
|
23
|
+
end
|
24
|
+
end
|
25
|
+
|
26
|
+
require "rubygems"
|
27
|
+
require "bundler/setup"
|
28
|
+
|
29
|
+
load Gem.bin_path("rake", "rake")
|
data/bin/rspec
ADDED
@@ -0,0 +1,29 @@
|
|
1
|
+
#!/usr/bin/env ruby
|
2
|
+
# frozen_string_literal: true
|
3
|
+
|
4
|
+
#
|
5
|
+
# This file was generated by Bundler.
|
6
|
+
#
|
7
|
+
# The application 'rspec' is installed as part of a gem, and
|
8
|
+
# this file is here to facilitate running it.
|
9
|
+
#
|
10
|
+
|
11
|
+
require "pathname"
|
12
|
+
ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile",
|
13
|
+
Pathname.new(__FILE__).realpath)
|
14
|
+
|
15
|
+
bundle_binstub = File.expand_path("../bundle", __FILE__)
|
16
|
+
|
17
|
+
if File.file?(bundle_binstub)
|
18
|
+
if File.read(bundle_binstub, 300) =~ /This file was generated by Bundler/
|
19
|
+
load(bundle_binstub)
|
20
|
+
else
|
21
|
+
abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run.
|
22
|
+
Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.")
|
23
|
+
end
|
24
|
+
end
|
25
|
+
|
26
|
+
require "rubygems"
|
27
|
+
require "bundler/setup"
|
28
|
+
|
29
|
+
load Gem.bin_path("rspec-core", "rspec")
|
@@ -0,0 +1,25 @@
|
|
1
|
+
require_relative '../lib/nested_array.rb'
|
2
|
+
require 'awesome_print'
|
3
|
+
|
4
|
+
a = [
|
5
|
+
{'id' => 1, 'parent_id' => nil, 'name' => 'category 1'},
|
6
|
+
{'id' => 2, 'parent_id' => nil, 'name' => 'category 2'},
|
7
|
+
{'id' => 3, 'parent_id' => 2, 'name' => 'category 3'},
|
8
|
+
{'id' => 4, 'parent_id' => nil, 'name' => 'category 4'},
|
9
|
+
{'id' => 5, 'parent_id' => 4, 'name' => 'category 5'},
|
10
|
+
{'id' => 6, 'parent_id' => 5, 'name' => 'category 6'},
|
11
|
+
{'id' => 7, 'parent_id' => nil, 'name' => 'category 7'},
|
12
|
+
{'id' => 8, 'parent_id' => 7, 'name' => 'category 8'},
|
13
|
+
{'id' => 9, 'parent_id' => 7, 'name' => 'category 9'},
|
14
|
+
{'id' => 10, 'parent_id' => 9, 'name' => 'category 10'},
|
15
|
+
{'id' => 11, 'parent_id' => 9, 'name' => 'category 11'}
|
16
|
+
]
|
17
|
+
|
18
|
+
b = a.shuffle
|
19
|
+
|
20
|
+
array = b.to_nested.nested_to_options
|
21
|
+
print 'array: '.red; p array
|
22
|
+
|
23
|
+
array.each do |v|
|
24
|
+
puts v[0]
|
25
|
+
end
|
data/lib/nested_array/nested.rb
CHANGED
@@ -7,12 +7,12 @@ module NestedArray::Nested
|
|
7
7
|
|
8
8
|
included do |recipient|
|
9
9
|
|
10
|
-
NESTED_OPTIONS
|
10
|
+
NESTED_OPTIONS ||= {
|
11
11
|
# Имена полей для получения/записи информации, чувствительны к string/symbol
|
12
|
-
id:
|
13
|
-
parent_id:
|
14
|
-
children:
|
15
|
-
level:
|
12
|
+
id: 'id',
|
13
|
+
parent_id: 'parent_id',
|
14
|
+
children: 'children',
|
15
|
+
level: 'level',
|
16
16
|
|
17
17
|
# Параметры для преобразования в nested
|
18
18
|
hashed: false,
|
@@ -31,9 +31,16 @@ module NestedArray::Nested
|
|
31
31
|
# Параматры для "склеивания" вложенных структур
|
32
32
|
path_separator: '-=path_separator=-',
|
33
33
|
path_key: 'text',
|
34
|
+
|
35
|
+
# Настройки формирования массива для опций тега <select>
|
36
|
+
option_value: 'id', # Что брать в качестве значений при формировании опций селекта.
|
37
|
+
option_text: 'name',
|
34
38
|
}
|
35
39
|
end
|
36
40
|
|
41
|
+
#
|
42
|
+
# Перебирает вложенную стуктуру.
|
43
|
+
#
|
37
44
|
def each_nested options={}
|
38
45
|
options = NESTED_OPTIONS.merge options
|
39
46
|
level = 0
|
@@ -47,8 +54,9 @@ module NestedArray::Nested
|
|
47
54
|
node = cache[level][i[level]]
|
48
55
|
i[level]+= 1
|
49
56
|
if node != nil
|
57
|
+
is_last_children = cache[level][i[level]].blank?
|
50
58
|
|
51
|
-
yield(node.clone, parents.clone, level)
|
59
|
+
yield(node.clone, parents.clone, level, is_last_children)
|
52
60
|
|
53
61
|
if !node[options[:children]].nil? && node[options[:children]].length > 0
|
54
62
|
level+= 1
|
@@ -248,14 +256,14 @@ module NestedArray::Nested
|
|
248
256
|
html+= options[:li]
|
249
257
|
html+= yield(node.clone, parents.clone, level)
|
250
258
|
|
251
|
-
if !node[:children].nil? && node[:children].length > 0
|
259
|
+
if !node[options[:children]].nil? && node[options[:children]].length > 0
|
252
260
|
level+= 1
|
253
261
|
html+= "\n" if !options[:inline]
|
254
262
|
html+= options[:tab] * (level * 2) if options[:tabulated]
|
255
263
|
html+= options[:ul]
|
256
264
|
html+= "\n" if !options[:inline]
|
257
265
|
parents[level] = node.clone
|
258
|
-
cache[level] = node[:children]
|
266
|
+
cache[level] = node[options[:children]]
|
259
267
|
i[level] = 0
|
260
268
|
else
|
261
269
|
html+= options[:_li]
|
@@ -274,7 +282,30 @@ module NestedArray::Nested
|
|
274
282
|
level-= 1
|
275
283
|
end
|
276
284
|
end
|
277
|
-
html
|
285
|
+
html.html_safe
|
286
|
+
end
|
287
|
+
|
288
|
+
#
|
289
|
+
# Возвращает массив для формирования опций html-тега <select>
|
290
|
+
# с псевдографикой, позволяющей вывести древовидную структуру.
|
291
|
+
# ```
|
292
|
+
# [['option_text1', 'option_value1'],['option_text2', 'option_value2'],…]
|
293
|
+
# ```
|
294
|
+
def nested_to_options options={}
|
295
|
+
options = NESTED_OPTIONS.merge options
|
296
|
+
ret = []
|
297
|
+
last = []
|
298
|
+
each_nested do |node, parents, level, is_last|
|
299
|
+
last[level+1] = is_last
|
300
|
+
node_text = node[options[:option_text]]
|
301
|
+
node_level = (1..level).map{|l| last[l] == true ? ' ' : '┃'}.join
|
302
|
+
node_last = is_last ? '┗' : '┣'
|
303
|
+
node_children = node[options[:children]].present? && node[options[:children]].length > 0 ? '┳' : '━'
|
304
|
+
option_text = "#{node_level}#{node_last}#{node_children}╸#{node_text}"
|
305
|
+
option_value = node[options[:option_value]]
|
306
|
+
ret.push [option_text, option_value]
|
307
|
+
end
|
308
|
+
ret
|
278
309
|
end
|
279
310
|
|
280
311
|
# "Скеивание" вложенных структур
|
data/lib/nested_array/version.rb
CHANGED
data/lib/nested_array.rb
CHANGED
metadata
CHANGED
@@ -1,14 +1,14 @@
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
2
2
|
name: nested_array
|
3
3
|
version: !ruby/object:Gem::Version
|
4
|
-
version: 1.
|
4
|
+
version: 1.1.0
|
5
5
|
platform: ruby
|
6
6
|
authors:
|
7
7
|
- zlatov
|
8
8
|
autorequire:
|
9
9
|
bindir: exe
|
10
10
|
cert_chain: []
|
11
|
-
date:
|
11
|
+
date: 2020-02-14 00:00:00.000000000 Z
|
12
12
|
dependencies:
|
13
13
|
- !ruby/object:Gem::Dependency
|
14
14
|
name: bundler
|
@@ -94,13 +94,21 @@ files:
|
|
94
94
|
- Gemfile
|
95
95
|
- Gemfile.lock
|
96
96
|
- LICENSE.txt
|
97
|
+
- README-ru.md
|
97
98
|
- README.md
|
98
99
|
- Rakefile
|
99
100
|
- bash/build/gem.sh
|
101
|
+
- bash/push/gem.sh
|
100
102
|
- bash/test/gem.sh
|
103
|
+
- bin/bundle
|
104
|
+
- bin/byebug
|
101
105
|
- bin/console
|
106
|
+
- bin/htmldiff
|
107
|
+
- bin/ldiff
|
108
|
+
- bin/rake
|
109
|
+
- bin/rspec
|
102
110
|
- bin/setup
|
103
|
-
-
|
111
|
+
- dev/nested_options.rb
|
104
112
|
- lib/nested_array.rb
|
105
113
|
- lib/nested_array/nested.rb
|
106
114
|
- lib/nested_array/version.rb
|