base_editing_bootstrap 0.1.2

Sign up to get free protection for your applications and to get access to all the features.
Files changed (86) hide show
  1. checksums.yaml +7 -0
  2. data/.rspec +3 -0
  3. data/.rubocop.yml +13 -0
  4. data/CHANGELOG.md +5 -0
  5. data/CODE_OF_CONDUCT.md +84 -0
  6. data/Dockerfile +57 -0
  7. data/LICENSE.txt +21 -0
  8. data/MIT-LICENSE +20 -0
  9. data/README.md +130 -0
  10. data/Rakefile +8 -0
  11. data/app/assets/config/base_editing_bootstrap_manifest.js +0 -0
  12. data/app/assets/images/base_editing_bootstrap/.keep +0 -0
  13. data/app/assets/stylesheets/base_editing_bootstrap/.keep +0 -0
  14. data/app/controllers/.keep +0 -0
  15. data/app/controllers/base_editing_controller.rb +209 -0
  16. data/app/controllers/concerns/.keep +0 -0
  17. data/app/controllers/restricted_area_controller.rb +26 -0
  18. data/app/helpers/.keep +0 -0
  19. data/app/helpers/base_editing_helper.rb +22 -0
  20. data/app/helpers/utilities/enum_helper.rb +24 -0
  21. data/app/helpers/utilities/form_helper.rb +61 -0
  22. data/app/helpers/utilities/modal_helper.rb +11 -0
  23. data/app/helpers/utilities/page_helper.rb +51 -0
  24. data/app/helpers/utilities/search_helper.rb +110 -0
  25. data/app/helpers/utilities/template_helper.rb +22 -0
  26. data/app/jobs/.keep +0 -0
  27. data/app/mailers/.keep +0 -0
  28. data/app/models/.keep +0 -0
  29. data/app/models/concerns/.keep +0 -0
  30. data/app/policies/base_model_policy.rb +42 -0
  31. data/app/views/.keep +0 -0
  32. data/app/views/base_editing/_edit_page_title_header.html.erb +3 -0
  33. data/app/views/base_editing/_editing_form_measure_unit.html.erb +15 -0
  34. data/app/views/base_editing/_form.html.erb +17 -0
  35. data/app/views/base_editing/_form_field.html.erb +6 -0
  36. data/app/views/base_editing/_form_field_header.html.erb +1 -0
  37. data/app/views/base_editing/_form_footer.html.erb +3 -0
  38. data/app/views/base_editing/_index_body.html.erb +17 -0
  39. data/app/views/base_editing/_index_main_buttons.html.erb +1 -0
  40. data/app/views/base_editing/_index_title_header.html.erb +10 -0
  41. data/app/views/base_editing/_navbar.html.erb +0 -0
  42. data/app/views/base_editing/_new_page_title_header.html.erb +3 -0
  43. data/app/views/base_editing/_search.html.erb +17 -0
  44. data/app/views/base_editing/_search_field.erb +4 -0
  45. data/app/views/base_editing/_search_footer.html.erb +1 -0
  46. data/app/views/base_editing/_search_result.html.erb +13 -0
  47. data/app/views/base_editing/_search_result_row.html.erb +8 -0
  48. data/app/views/base_editing/_tabs.html.erb +2 -0
  49. data/app/views/base_editing/cell_field/_base.html.erb +3 -0
  50. data/app/views/base_editing/cell_field/_timestamps.html.erb +3 -0
  51. data/app/views/base_editing/edit.html.erb +3 -0
  52. data/app/views/base_editing/form_field/_base.html.erb +7 -0
  53. data/app/views/base_editing/form_field/_date.html.erb +2 -0
  54. data/app/views/base_editing/form_field/_datetime.html.erb +2 -0
  55. data/app/views/base_editing/form_field/_decimal.html.erb +2 -0
  56. data/app/views/base_editing/form_field/_integer.html.erb +2 -0
  57. data/app/views/base_editing/index.html.erb +5 -0
  58. data/app/views/base_editing/new.html.erb +3 -0
  59. data/app/views/base_editing/show.html.erb +1 -0
  60. data/app/views/kaminari/_first_page.html.erb +3 -0
  61. data/app/views/kaminari/_gap.html.erb +3 -0
  62. data/app/views/kaminari/_last_page.html.erb +3 -0
  63. data/app/views/kaminari/_next_page.html.erb +3 -0
  64. data/app/views/kaminari/_page.html.erb +9 -0
  65. data/app/views/kaminari/_paginator.html.erb +17 -0
  66. data/app/views/kaminari/_prev_page.html.erb +3 -0
  67. data/base_editing_bootstrap.gemspec +39 -0
  68. data/cog.toml +26 -0
  69. data/config/initializers/base_field_error_proc.rb +1 -0
  70. data/config/locales/it.yml +67 -0
  71. data/config/routes.rb +2 -0
  72. data/docker-compose.yml +20 -0
  73. data/lib/base_editing_bootstrap/base_model.rb +30 -0
  74. data/lib/base_editing_bootstrap/engine.rb +15 -0
  75. data/lib/base_editing_bootstrap/forms/base.rb +101 -0
  76. data/lib/base_editing_bootstrap/is_validated.rb +20 -0
  77. data/lib/base_editing_bootstrap/searches/base.rb +47 -0
  78. data/lib/base_editing_bootstrap/searches/field.rb +18 -0
  79. data/lib/base_editing_bootstrap/version.rb +3 -0
  80. data/lib/base_editing_bootstrap.rb +26 -0
  81. data/lib/tasks/base_editing_bootstrap_tasks.rake +4 -0
  82. data/spec/support/external_shared/base_editing_controller_helpers.rb +154 -0
  83. data/spec/support/external_shared/base_model.rb +62 -0
  84. data/spec/support/external_shared/factory_bot.rb +28 -0
  85. data/spec/support/external_shared/pundit.rb +14 -0
  86. metadata +214 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: '08a32d00b8f2ec8a1b5898b42308ad3b663bfe222d8f7cd42cd94bae50b564f1'
4
+ data.tar.gz: 5f6154c097db9ea920cec28721799fec8d187fbeca4486d033d280230b029b81
5
+ SHA512:
6
+ metadata.gz: 4641e3d44871f28c5b01546060f55e4cd85cab31978bd14c2501ba0b9ca4967bb09852a8fd4ff52190f9923ebe10b689d40060fe17679ce1008abaf4e61ce97b
7
+ data.tar.gz: 2c1b036feca870757414e6dae00f11966356fe9f6cbb73ea80f1b8653ef670e30c87bb96443bb0f4ff1e949d7c4e5ac17d4b7c51b959ff206fc75b3bb8515859
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require rails_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,13 @@
1
+ AllCops:
2
+ TargetRubyVersion: 3.0
3
+
4
+ Style/StringLiterals:
5
+ Enabled: true
6
+ EnforcedStyle: double_quotes
7
+
8
+ Style/StringLiteralsInInterpolation:
9
+ Enabled: true
10
+ EnforcedStyle: double_quotes
11
+
12
+ Layout/LineLength:
13
+ Max: 120
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2024-04-06
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 TODO: Write your email address. 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/Dockerfile ADDED
@@ -0,0 +1,57 @@
1
+ # syntax = docker/dockerfile:1
2
+
3
+ # Make sure RUBY_VERSION matches the Ruby version in .ruby-version and Gemfile
4
+ ARG RUBY_VERSION=3.3.0
5
+ FROM registry.docker.com/library/ruby:$RUBY_VERSION-slim as base
6
+
7
+ # Rails app lives here
8
+ WORKDIR /app
9
+
10
+ # Set production environment
11
+ ENV RAILS_ENV="production"
12
+
13
+
14
+ # Throw-away build stage to reduce size of final image
15
+ FROM base as build_dev_image
16
+
17
+ # Install packages needed to build gems and node modules
18
+ RUN apt-get update -qq && \
19
+ apt-get install --no-install-recommends -y build-essential curl git libvips node-gyp pkg-config python-is-python3
20
+
21
+ # Install JavaScript dependencies
22
+ ARG NODE_VERSION=20.11.1
23
+ ARG YARN_VERSION=1.22.22
24
+ ENV PATH=/usr/local/node/bin:$PATH
25
+ RUN curl -sL https://github.com/nodenv/node-build/archive/master.tar.gz | tar xz -C /tmp/ && \
26
+ /tmp/node-build-master/bin/node-build "${NODE_VERSION}" /usr/local/node && \
27
+ npm install -g yarn@$YARN_VERSION && \
28
+ rm -rf /tmp/node-build-master
29
+
30
+ #------------------------------------------------------------
31
+ # IMMAGINE DI SVILUPPO
32
+ FROM build_dev_image as development_image
33
+
34
+ ARG default_editor
35
+ RUN apt-get install -y nano gpg gpg-agent git-lfs git ssh
36
+ #questo serve per editare le credentials
37
+ ENV EDITOR='nano' \
38
+ BUNDLE_PATH="/bundle"
39
+ # helper per webpacker
40
+ RUN touch /.yarnrc && chmod 777 /.yarnrc
41
+ RUN mkdir /.cache && chmod 777 /.cache
42
+ RUN adduser --system -D --uid 1000 -h /home/nobody --shell /bin/bash rails rails
43
+
44
+
45
+ RUN mkdir /bundle && chmod -R ugo+rwt /bundle
46
+ VOLUME /bundle
47
+
48
+ RUN gem install foreman
49
+ ##
50
+ # Installiamo:
51
+ # bundle-audit : gemma per controllo di sicurezza https://github.com/rubysec/bundler-audit
52
+ # bummr : gemma per upgrade automatizzato delle gemme con singoli commit per gemma
53
+ RUN gem install bundle-audit bummr
54
+
55
+ RUN mkdir -p /home/nobody && chmod 777 /home/nobody
56
+ ENV HOME="/home/nobody"
57
+
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024 Marino Bonetti
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/MIT-LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,130 @@
1
+ # BaseEditingBootstrap
2
+ WIP
3
+
4
+ ## Installation
5
+ Add this line to your application's Gemfile:
6
+
7
+ ```ruby
8
+ gem "base_editing_bootstrap"
9
+ ```
10
+
11
+ And then execute:
12
+ ```bash
13
+ $ bundle
14
+ ```
15
+
16
+ Or install it yourself as:
17
+ ```bash
18
+ $ gem install base_editing_bootstrap
19
+ ```
20
+
21
+ ### TODO generators
22
+ Then Install dependency (WIP TO TRANSLATE IN INSTALLATION TASK):
23
+ ```bash
24
+
25
+ bundle exec rails g pundit:install
26
+ ```
27
+ Aggiungere ad ApplicationController
28
+ ```ruby
29
+ include Pundit::Authorization
30
+ ```
31
+
32
+ Installare bootstrap e questo dipende dal sistema scelto di assets bundling.
33
+ La versione più semplice è attraverso: https://github.com/rails/cssbundling-rails
34
+ Una volta installato basta lanciare bin/rails css:install:bootstrap come da
35
+ documentazione e avrete la vostra versione di boostrap installata.
36
+
37
+ Installare `gem "factory_bot_rails"` e configurarlo correttamente in application.rb
38
+ ```ruby
39
+ config.generators do |g|
40
+ g.test_framework :rspec
41
+ g.fixture_replacement :factory_bot
42
+ g.factory_bot dir: 'spec/factories'
43
+ end
44
+ ```
45
+ ## Usage
46
+ Utilizzo per modello base, in questo esempio prendiamo come modello Post come esempio del dummy.
47
+
48
+ - Creare il Modello ed includere `include BaseEditingBootstrap::BaseModel`
49
+ - Creare Controller:
50
+ ```ruby
51
+ class PostsController < BaseEditingController
52
+ end
53
+ ```
54
+ - Aggiungere la rotta: `resources :posts`
55
+ - Creare la policy:
56
+ ```ruby
57
+ class PostPolicy < BaseModelPolicy
58
+
59
+ def editable_attributes
60
+ [
61
+ :title,
62
+ :description
63
+ ]
64
+ end
65
+
66
+ def permitted_attributes
67
+ [
68
+ :title,
69
+ :description
70
+ ]
71
+ end
72
+
73
+ def search_result_fields
74
+ [:title]
75
+ end
76
+ end
77
+
78
+ ```
79
+ - [OPTIONAL] nel caso si volesse fare override dei campi della form:
80
+ Per il campo che si vuole fare override creare un nuovo file nella cartella
81
+ del modello `app/views/posts/post/form_field/_NOME_CAMPO.html.erb`
82
+ al cui interno renderizzare il campo come si preferisce:
83
+ ```erbruby
84
+ <%# locals: (form:, field:) -%>
85
+ <%= form.text_field(field) %>
86
+ ```
87
+ - [OPTIONAL] la medesima cosa è possibile fare con il rendering dei campi
88
+ delle celle della tabella della pagina index.
89
+ La cartella da generare in questo caso sarà: `app/views/posts/post/cell_field/_NOME_CAMPO.html.erb`
90
+ ```erbruby
91
+ <%# locals: (obj:,field:) -%>
92
+ <td><%= obj.read_attribute(field) %></td>
93
+ ```
94
+ - [OPTIONAL] Base overrides:
95
+ E' possibile anche fare un override generico dei campi, sono previsti questi tipi di partial
96
+ legati al tipo di dati:
97
+ **Cell Field**:
98
+ - created_at => timestamps.html.erb
99
+ - updated_at => timestamps.html.erb
100
+ - default => base.html.erb
101
+ **Form Field**
102
+ - Integer => _integer.html.erb
103
+ - Float => _decimal.html.erb
104
+ - Decimal => _decimal.html.erb
105
+ - DateTime => _detetime.html.erb
106
+ - Date => _date.html.erb
107
+ - Default/String => _base.html.erb
108
+
109
+ In futuro si prevede di aggiungere automatismi per renderizzare senza
110
+ l'intervento dell'utente dei campi.
111
+ - [OPTIONAL] Search Form:
112
+ Per poter aggiungere una form di ricerca basta aggiungere alla policy
113
+ del modello in questione i campi di ricerca che verranno poi utilizzati da ransack
114
+ per eseguire le ricerche
115
+ ES:
116
+ ```ruby
117
+ # file app/policies/post_policy.rb
118
+ #...
119
+ def search_fields
120
+ [:title_i_cont]
121
+ end
122
+ #...
123
+ ```
124
+
125
+
126
+ ## Contributing
127
+ Contribution directions go here.
128
+
129
+ ## License
130
+ 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,8 @@
1
+ require "bundler/setup"
2
+
3
+ APP_RAKEFILE = File.expand_path("spec/dummy/Rakefile", __dir__)
4
+ load "rails/tasks/engine.rake"
5
+
6
+ load "rails/tasks/statistics.rake"
7
+
8
+ require "bundler/gem_tasks"
File without changes
File without changes
@@ -0,0 +1,209 @@
1
+ class BaseEditingController < RestrictedAreaController
2
+ before_action :load_object, only: [:edit, :update, :destroy]
3
+ helper_method :base_class,
4
+ :destroy_custom_polymorphic_path,
5
+ :edit_custom_polymorphic_path,
6
+ :form_attributes,
7
+ :form_builder,
8
+ :index_custom_polymorphic_path,
9
+ :new_custom_polymorphic_path,
10
+ :show_custom_polymorphic_path
11
+
12
+ def index
13
+ authorize base_class
14
+
15
+ q = policy_scope(base_scope)
16
+
17
+ @search_instance = search_class.new(q, current_user, params: params.permit(:page, :q => {})) # FIXME trovare modo per essere più "STRONG"
18
+ @search_instance = yield(@search_instance) if block_given?
19
+ end
20
+
21
+ def new
22
+ @object = base_class.new
23
+ @object = yield(@object) if block_given?
24
+ authorize @object
25
+
26
+ respond_to do |format|
27
+ format.html
28
+ end
29
+ end
30
+
31
+ def edit
32
+ @object = yield(@object) if block_given?
33
+ end
34
+
35
+ def update
36
+ @object = yield(@object) if block_given?
37
+ respond_to do |format|
38
+ if @object.update(permitted_attributes(@object))
39
+ _successful_update(format)
40
+ else
41
+ Rails.logger.debug { "#{base_class} non creato: #{@object.errors.messages.inspect}" }
42
+ _failed_update(format)
43
+ end
44
+ end
45
+ end
46
+
47
+ def create
48
+ @object = base_class.new(permitted_attributes)
49
+ @object = yield(@object) if block_given?
50
+ authorize @object
51
+
52
+ respond_to do |format|
53
+ if @object.save
54
+ _successful_create(format)
55
+ else
56
+ Rails.logger.debug { "#{base_class} non creato: #{@object.errors.messages.inspect}" }
57
+ _failed_create(format)
58
+ end
59
+ end
60
+ end
61
+
62
+ def destroy
63
+ @object = yield(@object) if block_given?
64
+
65
+ respond_to do |format|
66
+ if @object.destroy
67
+ _successful_destroy(format)
68
+ else
69
+ _failed_destroy(format)
70
+ end
71
+ end
72
+ end
73
+
74
+ protected
75
+
76
+ def base_class
77
+ return @_base_class if @_base_class
78
+ controller = controller_name
79
+ modello = controller.singularize.camelize.safe_constantize
80
+ logger.debug { "Editazione del controller:#{controller} per modello: #{modello.to_s}" }
81
+ raise "Non riesco a restituire la classe base per il controller #{controller}" if modello.nil?
82
+
83
+ @_base_class = modello
84
+ end
85
+
86
+ private
87
+
88
+ def search_class
89
+ BaseEditingBootstrap::Searches::Base
90
+ end
91
+
92
+ def form_builder
93
+ BaseEditingBootstrap::Forms::Base
94
+ end
95
+
96
+ def form_attributes(model = base_class.new, action = override_pundit_action_name)
97
+ policy = policy(model)
98
+ method_name = if policy.respond_to?("editable_attributes_for_#{action}")
99
+ "editable_attributes_for_#{action}"
100
+ else
101
+ "editable_attributes"
102
+ end
103
+ policy.public_send(method_name)
104
+ end
105
+
106
+ def load_object
107
+ @object = base_class.find(params[:id])
108
+ authorize @object
109
+ logger.debug { "Oggetto #{@object.inspect}" }
110
+ end
111
+
112
+ ##
113
+ # Scope iniziale per index, viene passato al policy_scope in index.
114
+ def base_scope
115
+ base_class
116
+ end
117
+
118
+ ##
119
+ # Semplice override per avere un debug
120
+ # @param record [ActiveRecord::Base] oggetto per cui estrapolare gli attributi ripuliti, di default utilizza
121
+ # la classe base
122
+ # @param [nil] action
123
+ # @return [Hash{String->Object}]
124
+ def permitted_attributes(record = base_class.new, action = override_pundit_action_name)
125
+ super.tap do |p|
126
+ Rails.logger.debug { "Permitted Attributes: #{pundit_params_for(record).inspect}" }
127
+ Rails.logger.debug { "Parametri puliti [#{action}]: #{p.inspect}" }
128
+ end
129
+ end
130
+
131
+ ##
132
+ # In casi in cui l'azione non è quella di pundit per poter ricercarne le policy
133
+ # possiamo fare override, altrimenti il default è l'action_name standard
134
+ def override_pundit_action_name
135
+ action_name
136
+ end
137
+
138
+ ##
139
+ # Versione più addolcita del require params, nel caso non sia presente il parametro corretto viene
140
+ # restituito un hash vuoto
141
+ def pundit_params_for(record)
142
+ params.fetch(Pundit::PolicyFinder.new(record).param_key, {})
143
+ end
144
+
145
+ def new_custom_polymorphic_path(*base_class)
146
+ new_polymorphic_path(*base_class)
147
+ end
148
+
149
+ def edit_custom_polymorphic_path(...)
150
+ edit_polymorphic_path(...)
151
+ end
152
+
153
+ def show_custom_polymorphic_path(...)
154
+ polymorphic_path(...)
155
+ end
156
+
157
+ def index_custom_polymorphic_path(...)
158
+ polymorphic_path(...)
159
+ end
160
+
161
+ def destroy_custom_polymorphic_path(...)
162
+ polymorphic_path(...)
163
+ end
164
+
165
+ def _failed_destroy(format)
166
+ format.all {
167
+ redirect_to index_custom_polymorphic_path(base_class),
168
+ flash: {error: @object.errors.full_messages.join(',')}
169
+ }
170
+ end
171
+
172
+ def _successful_destroy(format)
173
+ format.all do
174
+ redirect_to index_custom_polymorphic_path(base_class),
175
+ status: :see_other,
176
+ notice: t('activerecord.successful.messages.destroyed', model: base_class.model_name.human)
177
+ end
178
+ end
179
+
180
+ def _failed_create(format)
181
+ format.html do
182
+ flash.now.alert = t('activerecord.unsuccessful.messages.created', model: base_class.model_name.human)
183
+ render action: :new, status: :unprocessable_entity
184
+ end
185
+ end
186
+
187
+ def _successful_create(format)
188
+ format.all do
189
+ redirect_to edit_custom_polymorphic_path(@object),
190
+ status: :see_other,
191
+ notice: t('activerecord.successful.messages.created', model: base_class.model_name.human)
192
+ end
193
+ end
194
+
195
+ def _failed_update(format)
196
+ format.html do
197
+ flash.now.alert = t('activerecord.unsuccessful.messages.updated', model: base_class.model_name.human)
198
+ render action: :edit, status: :unprocessable_entity
199
+ end
200
+ end
201
+
202
+ def _successful_update(format)
203
+ format.all do
204
+ redirect_to edit_custom_polymorphic_path(@object),
205
+ status: :see_other,
206
+ notice: t('activerecord.successful.messages.updated', model: base_class.model_name.human)
207
+ end
208
+ end
209
+ end
File without changes
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ class RestrictedAreaController < BaseEditingBootstrap.inherited_controller.constantize
4
+ include Pundit::Authorization
5
+ after_action :verify_authorized
6
+ after_action :verify_policy_scoped, only: :index
7
+ rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized
8
+
9
+
10
+ # :nocov:
11
+ # Essendo un placeholder per after_action andiamo a non doverlo coprire con il coverage, se viene richiamato fallisce.
12
+ def index
13
+ raise "NOT implemented"
14
+ end
15
+
16
+ # :nocov:
17
+
18
+ private
19
+
20
+ def user_not_authorized(exception)
21
+ policy_name = exception.policy.class.to_s.underscore
22
+
23
+ flash[:error] = t "#{policy_name}.#{exception.query}", scope: "pundit", default: :default
24
+ redirect_back(fallback_location: root_path)
25
+ end
26
+ end
data/app/helpers/.keep ADDED
File without changes
@@ -0,0 +1,22 @@
1
+ module BaseEditingHelper
2
+ include Utilities::PageHelper
3
+ include Utilities::EnumHelper
4
+ include Utilities::SearchHelper
5
+ include Utilities::FormHelper
6
+
7
+
8
+ ##
9
+ # Genera le icone di Bootstrap icons
10
+ def icon( name, text = nil, html_options = {})
11
+ text, html_options = nil, text if text.is_a?(Hash)
12
+
13
+ content_class = "bi-#{name}"
14
+ content_class << " #{html_options[:class]}" if html_options.key?(:class)
15
+ html_options[:class] = content_class
16
+ html_options['aria-hidden'] ||= true
17
+
18
+ html = content_tag(:i, nil, html_options)
19
+ html << ' ' << text.to_s unless text.blank?
20
+ html
21
+ end
22
+ end
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Utilities
4
+ module EnumHelper
5
+ # @param [BaseModel] model class
6
+ # @param [Symbol] attribute
7
+ # @param [nil|String] variant
8
+ def enum_collection(model, attribute, variant = nil)
9
+ model.send(attribute.to_s.pluralize(2).to_sym).collect { |key, val|
10
+ [enum_translation(model, attribute, key, variant), key]
11
+ }.to_h
12
+ end
13
+
14
+ # @param [BaseModel] model class
15
+ # @param [Symbol] attribute
16
+ # @param [Symbol|nil] value
17
+ # @param [nil|String] variant
18
+ def enum_translation(model, attribute, value, variant = nil)
19
+ return '' if value.nil?
20
+ variant = "_#{variant}" unless variant.nil?
21
+ model.human_attribute_name("#{attribute}.#{value}#{variant}")
22
+ end
23
+ end
24
+ end