model_explorer 0.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.
Files changed (64) hide show
  1. checksums.yaml +7 -0
  2. data/.rspec +3 -0
  3. data/.rubocop.yml +8 -0
  4. data/.simplecov +17 -0
  5. data/CHANGELOG.md +5 -0
  6. data/CODE_OF_CONDUCT.md +84 -0
  7. data/LICENSE.txt +21 -0
  8. data/README.md +139 -0
  9. data/Rakefile +12 -0
  10. data/app/assets/config/model_explorer/manifest.js +2 -0
  11. data/app/assets/javascripts/model_explorer/application.js +5 -0
  12. data/app/assets/javascripts/model_explorer/association_manager.js +192 -0
  13. data/app/assets/javascripts/model_explorer/association_select.js +23 -0
  14. data/app/assets/javascripts/model_explorer/copy_button.js +25 -0
  15. data/app/assets/javascripts/model_explorer/model_form.js +61 -0
  16. data/app/assets/javascripts/model_explorer/models_controller.js +43 -0
  17. data/app/assets/stylesheets/model_explorer/application.css +7 -0
  18. data/app/assets/stylesheets/model_explorer/models.css +45 -0
  19. data/app/controllers/model_explorer/application_controller.rb +41 -0
  20. data/app/controllers/model_explorer/exports_controller.rb +53 -0
  21. data/app/controllers/model_explorer/models_controller.rb +23 -0
  22. data/app/serializers/application_serializer.rb +11 -0
  23. data/app/serializers/association_serializer.rb +21 -0
  24. data/app/serializers/model_serializer.rb +39 -0
  25. data/app/views/layouts/model_explorer/application.html.erb +28 -0
  26. data/app/views/model_explorer/models/index.html.erb +14 -0
  27. data/app/views/model_explorer/models/partials/_form.html.erb +49 -0
  28. data/app/views/model_explorer/models/partials/_record_details.html.erb +43 -0
  29. data/app/views/model_explorer/models/partials/_select_template.html.erb +53 -0
  30. data/config/locales/en.yml +3 -0
  31. data/config/locales/fr.yml +3 -0
  32. data/config/locales/views/layouts/model_explorer/application.en.yml +5 -0
  33. data/config/locales/views/layouts/model_explorer/application.fr.yml +5 -0
  34. data/config/locales/views/model_explorer/models/partials/form.en.yml +10 -0
  35. data/config/locales/views/model_explorer/models/partials/form.fr.yml +10 -0
  36. data/config/locales/views/model_explorer/models/partials/record_details.en.yml +9 -0
  37. data/config/locales/views/model_explorer/models/partials/record_details.fr.yml +9 -0
  38. data/config/locales/views/model_explorer/models/partials/select_template.en.yml +8 -0
  39. data/config/locales/views/model_explorer/models/partials/select_template.fr.yml +8 -0
  40. data/config/routes.rb +8 -0
  41. data/docs/example.png +0 -0
  42. data/lib/generators/model_explorer/USAGE +7 -0
  43. data/lib/generators/model_explorer/install_generator.rb +24 -0
  44. data/lib/generators/model_explorer/templates/model_explorer.rb.tt +24 -0
  45. data/lib/model_explorer/associations/base.rb +74 -0
  46. data/lib/model_explorer/associations/many.rb +43 -0
  47. data/lib/model_explorer/associations/singular.rb +19 -0
  48. data/lib/model_explorer/associations.rb +33 -0
  49. data/lib/model_explorer/engine.rb +39 -0
  50. data/lib/model_explorer/export.rb +53 -0
  51. data/lib/model_explorer/import.rb +64 -0
  52. data/lib/model_explorer/record.rb +15 -0
  53. data/lib/model_explorer/scopes.rb +23 -0
  54. data/lib/model_explorer/select.rb +28 -0
  55. data/lib/model_explorer/version.rb +5 -0
  56. data/lib/model_explorer.rb +77 -0
  57. data/sig/model_explorer.rbs +4 -0
  58. data/vendor/assets/javascripts/bootstrap.min.js +7 -0
  59. data/vendor/assets/javascripts/prism.min.js +4 -0
  60. data/vendor/assets/javascripts/tom_select.min.js +440 -0
  61. data/vendor/assets/stylesheets/bootstrap.min.css +6 -0
  62. data/vendor/assets/stylesheets/prism.min.css +3 -0
  63. data/vendor/assets/stylesheets/tom_select.min.css +15 -0
  64. metadata +128 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: c3811be2f5cc09b50878cdc5eca81109b11371856fd123f6bc2c5b69c5f402ef
4
+ data.tar.gz: cf2b513f5649fd251dc379fff78dcef816e5df4613754870a4e5e6bcdb1be81a
5
+ SHA512:
6
+ metadata.gz: f7eea4e8b21d7b0f637ed5fb5f92ac3eaef2038332e445c5551309b279c65383242615a2b1704eed9d3a35257cf88db911a6de38379bd3b5a963bcfe2eb2afe8
7
+ data.tar.gz: 7a31278d54503b90026cca17f4e73c54fc9f9c8689cfd28680ecb691aaacafe61de62f2a7700d07ee5dc5d9b2210a48e829b50f48a9c0fe460918a60717704bc
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,8 @@
1
+ AllCops:
2
+ TargetRubyVersion: 3.0
3
+
4
+ Style/StringLiterals:
5
+ EnforcedStyle: double_quotes
6
+
7
+ Style/StringLiteralsInInterpolation:
8
+ EnforcedStyle: double_quotes
data/.simplecov ADDED
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "simplecov_json_formatter"
4
+ require "model_explorer"
5
+
6
+ SimpleCov.formatters = SimpleCov::Formatter::MultiFormatter.new([
7
+ SimpleCov::Formatter::HTMLFormatter,
8
+ SimpleCov::Formatter::JSONFormatter
9
+ ])
10
+
11
+ SimpleCov.start do
12
+ add_group "ModelExplorer", ["model_explorer", "spec/features"]
13
+ add_group "Rails", ["/app/", "/config/", "spec/serializers", "spec/requests"]
14
+
15
+ add_filter "/spec/rails_helper.rb"
16
+ add_filter "/spec/rails_app/"
17
+ end
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2024-04-22
4
+
5
+ - Initial release
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at authiatv@gmail.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024 Victor
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,139 @@
1
+ # ModelExplorer
2
+
3
+ [![Build Status](https://github.com/victorauthiat/model_explorer/actions/workflows/build.yml/badge.svg)](https://github.com/victorauthiat/model_explorer/actions/workflows/build.yml)
4
+ [![Maintainability](https://api.codeclimate.com/v1/badges/9642bd2f42a045505fc2/maintainability)](https://codeclimate.com/github/VictorAuthiat/model_explorer/maintainability)
5
+ [![Test Coverage](https://api.codeclimate.com/v1/badges/9642bd2f42a045505fc2/test_coverage)](https://codeclimate.com/github/VictorAuthiat/model_explorer/test_coverage)
6
+
7
+ Rails gem to explore models attributes and their associations.
8
+
9
+ ![Example](docs/example.png)
10
+
11
+ Most of the time, the production database is not accessible, which makes debugging difficult. This gem gives you read access to the database by searching for a record and its associations.
12
+ You can also copy the result of a search and import it to test behavior from another test db.
13
+
14
+ It is highly recommended to use the basic auth feature to protect access to the search form.
15
+
16
+ ## Installation
17
+
18
+ Add this line to your application's Gemfile:
19
+
20
+ ```ruby
21
+ gem "model_explorer"
22
+ ```
23
+
24
+ And then execute:
25
+
26
+ ```bash
27
+ $ bundle install
28
+ ```
29
+
30
+ Run the following command to install the gem:
31
+
32
+ ```bash
33
+ $ bin/rails model_explorer:install
34
+ ```
35
+
36
+ This command will copy the initializer file to `config/initializers/model_explorer.rb`.
37
+
38
+ Add `--routes` to the command to add the engine routes to the `config/routes.rb` file or add the following line manually:
39
+
40
+ ```ruby
41
+ mount ModelExplorer::Engine => "/model_explorer"
42
+ ```
43
+
44
+ ### Basic Auth
45
+
46
+ To protect access to the search form, you can use the basic auth feature.
47
+
48
+ Uncomment the following lines in the initializer file to enable the feature:
49
+
50
+ ```ruby
51
+ ModelExplorer.configure do |config|
52
+ config.basic_auth_enabled = true
53
+ config.basic_auth_username = "admin"
54
+ config.basic_auth_password = "password"
55
+ end
56
+ ```
57
+
58
+ ### Custom Access Control
59
+
60
+ You can also define a custom access control to restrict access to the search form.
61
+
62
+ Uncomment the following lines in the initializer file to enable verification:
63
+
64
+ ```ruby
65
+ ModelExplorer.configure do |config|
66
+ config.verify_access_proc = ->(controller) do
67
+ controller.current_admin_user&.super_admin?
68
+ end
69
+ end
70
+ ```
71
+
72
+ The `verify_access_proc` is a lambda that receives the controller instance and returns a boolean value.
73
+
74
+ ## Filter attributes
75
+
76
+ You can filter sensitive attributes as follows:
77
+
78
+ ```ruby
79
+ ModelExplorer.configure do |config|
80
+ config.filter_attributes_regexp = /api_key|api_secret/i
81
+ end
82
+ ```
83
+
84
+ By default, the `filter_attributes_regexp` is set to `/password|secret/token/i`.
85
+
86
+
87
+ ## Maximum Items per Association
88
+
89
+ Set the maximum number of options in association selects
90
+
91
+ ```ruby
92
+ ModelExplorer.configure do |config|
93
+ config.max_items_per_association = 5
94
+ end
95
+ ```
96
+
97
+ To completely disable association dropdowns (i.e., the select will not be displayed in the search form), set the maximum items to 0.
98
+
99
+ ## Maximum Scopes per Association
100
+
101
+ Control the number of scopes available in scope dropdowns by configuring the maximum allowed as follows:
102
+
103
+ ```ruby
104
+ ModelExplorer.configure do |config|
105
+ config.max_scopes_per_association = 5
106
+ end
107
+ ```
108
+
109
+ Similar to item associations, scopes can also be completely disabled by setting the maximum to 0.
110
+
111
+ ## Importing data
112
+
113
+ You can import data as follows:
114
+
115
+ 1. Search for a record and its associations.
116
+ 2. Copy the result of the search.
117
+ 3. Go to your spec file and import the result as follows:
118
+
119
+ ```ruby
120
+ let(:user) { ModelExplorer.import(File.read("spec/fixtures/test_user.json")) }
121
+ ```
122
+
123
+ ## Development
124
+
125
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. For headless testing using Capybara and Selenium with Chrome, use: `CAPYBARA_DRIVER=selenium_chrome_headless rake spec`. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
126
+
127
+ 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 the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
128
+
129
+ ## Contributing
130
+
131
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/model_explorer. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/[USERNAME]/model_explorer/blob/master/CODE_OF_CONDUCT.md).
132
+
133
+ ## License
134
+
135
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
136
+
137
+ ## Code of Conduct
138
+
139
+ Everyone interacting in the ModelExplorer project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/model_explorer/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
@@ -0,0 +1,2 @@
1
+ //= link ../../../stylesheets/model_explorer .css
2
+ //= link ../../../javascripts/model_explorer .js
@@ -0,0 +1,5 @@
1
+ //= require tom_select.min
2
+ //= require bootstrap.min
3
+ //= require prism.min
4
+
5
+ //= require_tree .
@@ -0,0 +1,192 @@
1
+ class AssociationManager {
2
+ constructor({ templateId }) {
3
+ this.template = document.getElementById(templateId);
4
+ this.maxItems = this.template.dataset.maxItems || 5;
5
+ this.maxScopes = this.template.dataset.maxScopes || 5;
6
+ }
7
+
8
+ async addAssociation(associationSelect, association) {
9
+ try {
10
+ const option = associationSelect.selectElement.querySelector(`option[value="${association}"]`);
11
+ const parent = associationSelect.selectElement.dataset.relation;
12
+ const requestPath = this._constructRequestPath(option, parent);
13
+ const response = await fetch(requestPath);
14
+ const data = await response.json();
15
+
16
+ this.addAssociationsSelect(option, associationSelect, data);
17
+ } catch (error) {
18
+ console.error("Failed to add association:", error);
19
+ }
20
+ }
21
+
22
+ addAssociationsSelect(option, associationSelect, data) {
23
+ if (data.associations.length === 0) return;
24
+
25
+ const templateClone = this.template.content.cloneNode(true);
26
+ const newContainer = document.createElement('div');
27
+ const relationName = this._constructRelationName(option.value);
28
+ const associationId = this._constructId(associationSelect.selectElement.dataset.relation, relationName);
29
+
30
+ newContainer.appendChild(templateClone);
31
+ newContainer.innerHTML = newContainer.innerHTML.replace(/TEMP_ID/g, associationId);
32
+ newContainer.querySelector('.card-header').textContent = option.value;
33
+
34
+ this._populateInputs(newContainer, associationSelect, option);
35
+ this._populateAssociationsSelect(newContainer, data.associations, associationId);
36
+ this._initializeNewAssociationSelect(newContainer, associationId, associationSelect);
37
+ this._populateScopesSelect(newContainer, data.scopes, associationId);
38
+ this._initializeNewScopeSelect(newContainer, associationId, associationSelect);
39
+ this._populateColumnsSelect(newContainer, data.columns, associationId);
40
+ this._initializeNewColumnsSelect(newContainer, associationId, associationSelect);
41
+ }
42
+
43
+ removeAssociation(associationSelect, association) {
44
+ const parentRelation = associationSelect.selectElement.dataset.relation;
45
+
46
+ if (!parentRelation) {
47
+ document.getElementById(`associations-accordion-${this._constructRelationName(association)}`).remove();
48
+ } else {
49
+ const fullAssociation = `${parentRelation}-${association}`;
50
+ document.getElementById(`associations-accordion-${fullAssociation}`).remove();
51
+ }
52
+ }
53
+
54
+ _constructRequestPath(option, parent) {
55
+ const modelName = option.dataset.model || option.value;
56
+ const macroName = option.dataset.macro;
57
+
58
+ let requestPath = `/model_explorer/models/${modelName}`;
59
+ requestPath += macroName ? `?macro=${macroName}` : '';
60
+ requestPath += parent ? `&parent=${parent}` : '';
61
+
62
+ return requestPath;
63
+ }
64
+
65
+ _constructRelationName(name) {
66
+ return name
67
+ .replace(/::/g, '_')
68
+ .replace(/([A-Z])/g, (match, offset) => offset > 0 ? '_' + match.toLowerCase() : match.toLowerCase())
69
+ }
70
+
71
+ _constructName(input, associationSelect) {
72
+ if (associationSelect.parent) {
73
+ const parentRelation = associationSelect.selectElement.dataset.relation;
74
+ const parentInput = document.getElementById(`associations-input-${parentRelation}`);
75
+ const parentName = parentInput.name.replace('[name]', '');
76
+ const inputIndex = input.dataset.index;
77
+
78
+ return `${parentName}[associations][${inputIndex}][association_attributes][name]`;
79
+ } else {
80
+ return 'association_attributes[name]';
81
+ }
82
+ }
83
+
84
+ _constructId(parentRelation, relationName) {
85
+ return parentRelation ? `${parentRelation}-${relationName}` : relationName;
86
+ }
87
+
88
+ _populateInputs(container, associationSelect, option) {
89
+ const parentInputs = associationSelect.associationContainer.querySelectorAll('input:not([id*="ts-control"])');
90
+ const input = container.querySelector('input');
91
+
92
+ input.setAttribute('data-index', parentInputs.length);
93
+ input.name = this._constructName(input, associationSelect);
94
+ input.value = option.value;
95
+ }
96
+
97
+ _populateAssociationsSelect(container, associations, associationId) {
98
+ const select = container.querySelector(`#associations-select-${associationId}`);
99
+
100
+ if (!select) return;
101
+
102
+ select.setAttribute('data-relation', associationId);
103
+
104
+ associations.forEach(assoc => {
105
+ const option = document.createElement('option');
106
+ option.value = assoc.name;
107
+ option.textContent = assoc.name;
108
+ option.dataset.model = assoc.model;
109
+ option.dataset.macro = assoc.macro;
110
+ select.appendChild(option);
111
+ });
112
+ }
113
+
114
+ _populateScopesSelect(container, scopes, associationId) {
115
+ const select = container.querySelector(`#scopes-select-${associationId}`);
116
+
117
+ if (!select) return;
118
+
119
+ select.setAttribute('data-relation', associationId);
120
+
121
+ scopes.forEach(scope => {
122
+ const option = document.createElement('option');
123
+ option.value = scope;
124
+ option.textContent = scope;
125
+ select.appendChild(option);
126
+ });
127
+ }
128
+
129
+ _initializeNewAssociationSelect(container, associationId, associationSelect) {
130
+ associationSelect.associationContainer.appendChild(container);
131
+
132
+ const newAssociationSelect = new AssociationSelect({
133
+ selectId: `associations-select-${associationId}`,
134
+ ContainerId: `associations-container-${associationId}`,
135
+ parentId: associationSelect.selectElement.id
136
+ });
137
+
138
+ newAssociationSelect.initialize(this, { maxItems: this.maxItems });
139
+ }
140
+
141
+ _initializeNewScopeSelect(container, associationId, associationSelect) {
142
+ const parentInputs = associationSelect.associationContainer.querySelectorAll('input:not([id*="ts-control"])');
143
+ const select = container.querySelector(`#scopes-select-${associationId}`);
144
+
145
+ if (!select) return;
146
+
147
+ if (select.children.length === 0 || (parentInputs.length - 1) === 0) {
148
+ select.remove();
149
+ return;
150
+ }
151
+
152
+ select.setAttribute('data-index', parentInputs.length - 1);
153
+ const name = this._constructName(select, associationSelect).replace('[name]', '[scopes][]');
154
+ select.name = name
155
+
156
+ associationSelect.associationContainer.appendChild(container);
157
+ new TomSelect(`#scopes-select-${associationId}`, { maxItems: this.maxScopes });
158
+ }
159
+
160
+ _populateColumnsSelect(container, columns, associationId) {
161
+ const select = container.querySelector(`#columns-select-${associationId}`);
162
+
163
+ select.setAttribute('data-relation', associationId);
164
+
165
+ columns.forEach(column => {
166
+ const option = document.createElement('option');
167
+ option.value = column;
168
+ option.textContent = column;
169
+ select.appendChild(option);
170
+ });
171
+ }
172
+
173
+ _initializeNewColumnsSelect(container, associationId, associationSelect) {
174
+ const parentInputs = associationSelect.associationContainer.querySelectorAll('input:not([id*="ts-control"])');
175
+ const select = container.querySelector(`#columns-select-${associationId}`);
176
+
177
+ select.setAttribute('data-index', parentInputs.length - 1);
178
+
179
+ let name;
180
+
181
+ if ((parentInputs.length - 1) === 0) {
182
+ name = 'columns[]';
183
+ } else {
184
+ name = this._constructName(select, associationSelect).replace('[name]', '[columns][]');
185
+ }
186
+
187
+ select.name = name
188
+
189
+ associationSelect.associationContainer.appendChild(container);
190
+ new TomSelect(`#columns-select-${associationId}`);
191
+ }
192
+ }
@@ -0,0 +1,23 @@
1
+ class AssociationSelect {
2
+ constructor({selectId, ContainerId, parentId = null}) {
3
+ this.selectElement = document.getElementById(selectId);
4
+ this.associationContainer = document.getElementById(ContainerId);
5
+
6
+ if (parentId) {
7
+ this.parent = document.getElementById(parentId);
8
+ }
9
+ }
10
+
11
+ initialize(manager, options = {}) {
12
+ if (!this.selectElement) return;
13
+
14
+ new TomSelect(
15
+ this.selectElement,
16
+ {
17
+ ...options,
18
+ onItemAdd: (item) => manager.addAssociation(this, item),
19
+ onItemRemove: (item) => manager.removeAssociation(this, item)
20
+ }
21
+ );
22
+ }
23
+ }
@@ -0,0 +1,25 @@
1
+ class CopyButton {
2
+ constructor({copyButtonId, targetId}) {
3
+ this.copyButton = document.getElementById(copyButtonId);
4
+ this.target = document.getElementById(targetId);
5
+ }
6
+
7
+ initialize() {
8
+ this.copyButton.addEventListener('click', () => {
9
+ const textarea = document.createElement('textarea');
10
+ const copyButtonHtml = this.copyButton.innerHTML;
11
+
12
+ textarea.value = this.target.textContent;
13
+ document.body.appendChild(textarea);
14
+ textarea.select();
15
+ document.execCommand('copy');
16
+ document.body.removeChild(textarea);
17
+
18
+ this.copyButton.textContent = this.copyButton.dataset.text;
19
+
20
+ setTimeout(() => {
21
+ this.copyButton.innerHTML = copyButtonHtml;
22
+ }, 1000);
23
+ });
24
+ }
25
+ }
@@ -0,0 +1,61 @@
1
+ class ModelForm {
2
+ constructor({ formId, recordDetailsId, noRecordId, recordDetailsLinkId, downloadLinkId }) {
3
+ this.form = document.getElementById(formId);
4
+ this.recordDetails = document.getElementById(recordDetailsId);
5
+ this.recordDetailsPre = this.recordDetails.querySelector('pre');
6
+ this.noRecord = document.getElementById(noRecordId);
7
+ this.viewRecordDetailsLink = document.getElementById(recordDetailsLinkId);
8
+ this.downloadLink = document.getElementById(downloadLinkId);
9
+ }
10
+
11
+ initialize() {
12
+ this.form.addEventListener('submit', async (event) => {
13
+ event.preventDefault();
14
+
15
+ this.form.classList.add('was-validated');
16
+
17
+ if (!this.form.checkValidity()) {
18
+ return;
19
+ }
20
+
21
+ const response = await fetch(
22
+ this._collectFormData(),
23
+ { method: 'GET' }
24
+ ).then(response => response.text()).then(json => JSON.parse(json));
25
+
26
+ this._updateRecordDetails(response);
27
+ });
28
+ }
29
+
30
+ _collectFormData() {
31
+ const url = new URL(this.form.action);
32
+ const params = new URLSearchParams();
33
+
34
+ Array.from(this.form.elements).forEach(element => {
35
+ if (element.name) {
36
+ if (element.multiple) {
37
+ Array.from(element.selectedOptions).forEach(option => {
38
+ params.append(element.name, option.value);
39
+ });
40
+ } else {
41
+ params.append(element.name, element.value);
42
+ }
43
+ }
44
+ });
45
+
46
+ url.search = params.toString();
47
+
48
+ return url;
49
+ }
50
+
51
+ _updateRecordDetails(parsedResponse) {
52
+ const content = parsedResponse.error === undefined ? parsedResponse.export : parsedResponse;
53
+
54
+ this.downloadLink.href = parsedResponse.path;
55
+ this.viewRecordDetailsLink.href = parsedResponse.path;
56
+ this.recordDetailsPre.textContent = JSON.stringify(content, null, 3);
57
+ Prism.highlightElement(this.recordDetailsPre);
58
+ this.noRecord.classList.add('d-none');
59
+ this.recordDetails.classList.remove('d-none');
60
+ }
61
+ }
@@ -0,0 +1,43 @@
1
+ class ModelsController {
2
+ constructor() {
3
+ this.modelForm = new ModelForm({
4
+ recordDetailsId: 'json-data',
5
+ noRecordId: 'no-record',
6
+ formId: 'export-form',
7
+ recordDetailsLinkId: 'view-record-details',
8
+ downloadLinkId: 'download-record-details'
9
+ });
10
+
11
+ this.associationSelect = new AssociationSelect({
12
+ ContainerId: 'associations-container',
13
+ selectId: 'association-select',
14
+ parentId: null
15
+ });
16
+
17
+ this.associationManager = new AssociationManager({
18
+ templateId: 'associations-select-template'
19
+ });
20
+
21
+ this.recordDetailsCopyButton = new CopyButton({
22
+ copyButtonId: 'copy-record-details',
23
+ targetId: 'json-pre'
24
+ });
25
+ }
26
+
27
+ connect() {
28
+ this.modelForm.initialize();
29
+ this.associationSelect.initialize(this.associationManager, { maxItems: 1});
30
+ this.recordDetailsCopyButton.initialize();
31
+
32
+ document.querySelectorAll('select option').forEach(option => {
33
+ option.setAttribute('data-model', option.value);
34
+ option.setAttribute('data-relation', option.value.replace(/::/g, '_').toLowerCase());
35
+ });
36
+ }
37
+ }
38
+
39
+ document.addEventListener('DOMContentLoaded', function () {
40
+ const modelsController = new ModelsController();
41
+
42
+ modelsController.connect();
43
+ });
@@ -0,0 +1,7 @@
1
+ /*
2
+ *= require tom_select.min
3
+ *= require bootstrap.min
4
+ *= require prism.min
5
+
6
+ *= require_tree .
7
+ */