status_assignable 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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 619499be038a8c119a14b9b66a7bf0b922b018c14a4258ccff64c94ca255407d
4
+ data.tar.gz: 9e34b56aff3b351b09ca01f6d220d6d38cb5af097c7394f09f63db4aced48b2c
5
+ SHA512:
6
+ metadata.gz: afa83054aab31159694681db991ad7470083bc07ec3869abfb7b1c2f958988f1c069622da27633d98dce610cd3f6de2da52e197db1d8125605754b2f0d800f18
7
+ data.tar.gz: 84b0626e4ebde55f1a6828c935e1b68f07ac1e3c76ca1bd15b82806cd22b2ee0b1df3deba52009b27b7085027d5c786465df02456c8d0e1cda8811ef7f4a25bf
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,6 @@
1
+ require:
2
+ - rubocop-rake
3
+
4
+ AllCops:
5
+ TargetRubyVersion: 3.0
6
+ NewCops: enable
@@ -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/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024 TODO: Write your name
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,125 @@
1
+ # Status Assignable
2
+
3
+ ## Installation
4
+
5
+ Add this line to your application's Gemfile:
6
+
7
+ ```ruby
8
+ gem 'status_assignable', git: 'https://github.com/tieeeeen1994/rails-status-assignable'
9
+ ```
10
+
11
+ After that, run the following command:
12
+ ```bash
13
+ rails g status_assignable_patch
14
+ ```
15
+
16
+ This will install the monkey patcher so that the gem can hook itself properly into the Rails application.
17
+
18
+ ## Usage
19
+
20
+ ### Model
21
+
22
+ In your model, add the following line:
23
+
24
+ ```ruby
25
+ class ModelName < ApplicationRecord
26
+ include StatusAssignable
27
+
28
+ # ...
29
+ end
30
+ ```
31
+
32
+ Then add a new migration that will add a status column to the model's database table:
33
+
34
+ ```bash
35
+ rails g migration AddStatusToModelName
36
+ ```
37
+
38
+ ```ruby
39
+ class AddStatusToModelName < ActiveRecord::Migration[<RAILS VERSION>]
40
+ def change
41
+ add_column :model_names, :status, :integer, default: 1
42
+ # 0 = deleted, 1 = active, 2 = inactive
43
+ end
44
+ end
45
+ ```
46
+
47
+ Your model is now status assignable!
48
+
49
+ ```ruby
50
+ my_model = ModelName.find(1)
51
+ my_model.inactive! # Set the status to inactive
52
+ my_model.inactive? # true
53
+ my_model.deleted! # Set the status to deleted
54
+ my_model.deleted? # true
55
+ my_model.active! # Set the status to active
56
+ my_model.active? # true
57
+ my_model.soft_destroy # Archive the record with callbacks and its associations
58
+ my_model.archive # Alias of soft_destroy
59
+ my_model.soft_delete # Directly update the column in the database and also update its associations
60
+ ```
61
+
62
+ #### Custom Status
63
+
64
+ You can also add your own status if need be. For example, if you want to add a `pending` status:
65
+
66
+ ```ruby
67
+ class ModelName < ApplicationRecord
68
+ include StatusAssignable[pending: 3]
69
+ # ...
70
+ end
71
+ ```
72
+
73
+ This will add a `pending` status for your model. You can then use it like so:
74
+
75
+ ```ruby
76
+ my_model = ModelName.find(1)
77
+ my_model.pending! # Set the status to pending
78
+ my_model.pending? # true
79
+ ```
80
+
81
+ **Take note that the application will raise an exception if the default statuses are overridden. Use different key-value pair for your custom status if that happens.**
82
+
83
+ ### Associations
84
+
85
+ Model associations are also supported. For example, if you have a `User` that has many `Post`s and `Comment`s, you can add the following line to the `User` model:
86
+
87
+ ```ruby
88
+ class User < ApplicationRecord
89
+ include StatusAssignable
90
+
91
+ has_many :posts, dependent: :destroy, archive: :callbacks
92
+ has_many :comments, dependent: :delete_all, archive: :assign
93
+ end
94
+ ```
95
+
96
+ The `archive` option can be set to `:callbacks` or `:assign`. If set to `:callbacks`, the associated records will be archived using `soft_destroy`. If set to `:assign`, the associated records will have their status columns assigned directly.
97
+
98
+ It is important that the associations also are `StatusAssignable`!
99
+
100
+ ### Callbacks
101
+
102
+ Callbacks are only fired when `archive` or `soft_destroy` is called. `soft_delete` **never** fires callbacks (the association will use callbacks if it has the `archive: :callbacks` option).
103
+
104
+ There are callback hooks supported for `soft_destroy`: `before_soft_destroy`, `around_soft_destroy`, `after_soft_destroy`. They work like any model callbacks, so use them if need be when archiving a record.
105
+
106
+ ```ruby
107
+ class Post < ApplicationRecord
108
+ include StatusAssignable
109
+
110
+ before_destroy -> { versions.destroy_all }
111
+ before_soft_destroy :update_and_unlink_versions
112
+ end
113
+ ```
114
+
115
+ ## Contributing
116
+
117
+ Bug reports and pull requests are welcome on GitHub at https://github.com/tieeeeen1994/status_assignable. 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]/status_assignable/blob/master/CODE_OF_CONDUCT.md).
118
+
119
+ ## License
120
+
121
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
122
+
123
+ ## Code of Conduct
124
+
125
+ Everyone interacting in the Status Assignable project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/status_assignable/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rubocop/rake_task'
5
+
6
+ RuboCop::RakeTask.new
7
+
8
+ task default: %i[rubocop]
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Generates a patch for Rails so that status assignable models can have their associations archived when soft deleted.
4
+ class StatusAssignablePatchGenerator < Rails::Generators::Base
5
+ source_root File.expand_path('templates', __dir__)
6
+
7
+ def create_patch_file
8
+ template 'monkey_patch.rb.erb', File.join('config/initializers/status_assignable.rb')
9
+ end
10
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ Rails.application.reloader.to_prepare do
4
+ ActiveRecord::Associations::Builder::Association.singleton_class.prepend StatusAssignable::Association
5
+ end
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ module StatusAssignable
4
+ # This will allow the model to allow custom :archive option to be valid.
5
+ # The values accepted by the :archive option are :callbacks and :assign.
6
+ module Association
7
+ CUSTOM_VALID_OPTIONS = [:archive].freeze
8
+ VALID_ARCHIVE_OPTIONS = %i[callbacks assign].freeze
9
+
10
+ private
11
+
12
+ def valid_options(options)
13
+ super(options) + CUSTOM_VALID_OPTIONS
14
+ end
15
+
16
+ def define_callbacks(model, reflection)
17
+ if (archive_option_value = reflection.options[:archive])
18
+ check_archive_options(archive_option_value)
19
+ end
20
+ super(model, reflection)
21
+ end
22
+
23
+ def check_archive_options(archive_option_value)
24
+ return if VALID_ARCHIVE_OPTIONS.include? archive_option_value
25
+
26
+ message = "The :archive option must be one of #{VALID_ARCHIVE_OPTIONS}, but is :#{archive_option_value}"
27
+ raise ArgumentError, message
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module StatusAssignable
4
+ VERSION = '0.1.0'
5
+ end
@@ -0,0 +1,105 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'status_assignable/version'
4
+ require_relative 'status_assignable/association'
5
+
6
+ # Allows for soft deletion of records.
7
+ # Include this module in your model to enable soft deletion.
8
+ # e.g:
9
+ # class User < ApplicationRecord
10
+ # include StatusAssignable
11
+ # end
12
+ # This requires a status column with type integer to be present in the model's table.
13
+ module StatusAssignable
14
+ extend ActiveSupport::Concern
15
+
16
+ DEFAULT_STATUSES = { deleted: 0, active: 1, inactive: 2 }.freeze
17
+
18
+ def self.status_dictionary
19
+ @status_dictionary || { deleted: 0, active: 1, inactive: 2 }
20
+ end
21
+
22
+ def self.clear_dictionary
23
+ @status_dictionary = nil
24
+ end
25
+
26
+ # Allows adding custom statuses to the model's status enum.
27
+ # @param [Hash<Symbol, Integer>] status_dictionary Custom statuses to add.
28
+ # @return [StatusAssignable] Itself.
29
+ def self.[](status_dictionary)
30
+ resulting_statuses = DEFAULT_STATUSES.merge(status_dictionary)
31
+ raise ArgumentError, "Default statuses overridden. Don't do this." unless resulting_statuses >= DEFAULT_STATUSES
32
+ unless resulting_statuses.values.uniq.length == resulting_statuses.values.length
33
+ raise ArgumentError, 'Status values must be unique.'
34
+ end
35
+
36
+ @status_dictionary = resulting_statuses
37
+ self
38
+ end
39
+
40
+ included do # rubocop:disable Metrics/BlockLength
41
+ define_callbacks :soft_destroy, scope: %i[kind name]
42
+ enum status: StatusAssignable.status_dictionary
43
+ StatusAssignable.clear_dictionary
44
+
45
+ # Updates the status of the record directly to the database.
46
+ # @return [self, Boolean] Itself if true or false if failed.
47
+ def soft_delete
48
+ result = transaction do
49
+ archive_associations
50
+ update_columns(archive_params)
51
+ end
52
+ result ? self : false
53
+ end
54
+
55
+ # Updates the record through back to back callbacks.
56
+ # @return [<Type>] Itself if true or false if failed.
57
+ def soft_destroy
58
+ result = transaction do
59
+ run_callbacks :soft_destroy do
60
+ archive_associations
61
+ set_paper_trail_event
62
+ update(archive_params)
63
+ end
64
+ end
65
+ result ? self : false
66
+ end
67
+
68
+ alias_method :archive, :soft_destroy
69
+
70
+ private
71
+
72
+ def paper_trail_enabled?
73
+ defined?(PaperTrail) && PaperTrail.request.enabled_for_model?(self.class)
74
+ end
75
+
76
+ def set_paper_trail_event
77
+ # This uses PaperTrail's on_update method instead of destroy.
78
+ # However, the code sets it to destroy event due to the nature of the library.
79
+ self.paper_trail_event = 'destroy' if paper_trail_enabled?
80
+ end
81
+
82
+ def archive_params
83
+ @archive_params ||= { status: 'deleted', updated_at: Time.current }
84
+ end
85
+
86
+ def archivable_associations
87
+ @archivable_associations ||= self.class.reflect_on_all_associations.select do |association|
88
+ association.options[:archive]
89
+ end
90
+ end
91
+
92
+ def archive_associations
93
+ archivable_associations.each do |association|
94
+ archive_procedure = association.options[:archive]
95
+ query = send(association.name)
96
+ case archive_procedure
97
+ when :callbacks
98
+ query.respond_to?(:each) ? query.each(&:soft_destroy) : query.soft_destroy
99
+ when :assign
100
+ query.respond_to?(:update_all) ? query.update_all(archive_params) : query.update_columns(archive_params)
101
+ end
102
+ end
103
+ end
104
+ end
105
+ end
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'lib/status_assignable/version'
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = 'status_assignable'
7
+ spec.version = StatusAssignable::VERSION
8
+ spec.authors = ['Tien']
9
+ spec.email = ['tieeeeen1994@gmail.com']
10
+ spec.summary = 'Allows models to be assigned a status.'
11
+ spec.homepage = 'https://github.com/tieeeeen1994/rails-status-assignable'
12
+ spec.license = 'MIT'
13
+ spec.required_ruby_version = '>= 3.0.0'
14
+ spec.metadata['homepage_uri'] = spec.homepage
15
+
16
+ # Specify which files should be added to the gem when it is released.
17
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
18
+ spec.files = Dir.chdir(__dir__) do
19
+ `git ls-files -z`.split("\x0").reject do |f|
20
+ (File.expand_path(f) == __FILE__) ||
21
+ f.start_with?(*%w[bin/ test/ spec/ features/ .git .github appveyor Gemfile])
22
+ end
23
+ end
24
+ spec.bindir = 'exe'
25
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
26
+ spec.require_paths = ['lib']
27
+
28
+ # Uncomment to register a new dependency of your gem
29
+ spec.add_dependency 'rails', '~> 7.1'
30
+
31
+ # For more information and examples about making a new gem, check out our
32
+ # guide at: https://bundler.io/guides/creating_gem.html
33
+ spec.metadata['rubygems_mfa_required'] = 'true'
34
+ end
metadata ADDED
@@ -0,0 +1,71 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: status_assignable
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Tien
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2024-03-27 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: rails
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '7.1'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '7.1'
27
+ description:
28
+ email:
29
+ - tieeeeen1994@gmail.com
30
+ executables: []
31
+ extensions: []
32
+ extra_rdoc_files: []
33
+ files:
34
+ - ".rspec"
35
+ - ".rubocop.yml"
36
+ - CODE_OF_CONDUCT.md
37
+ - LICENSE.txt
38
+ - README.md
39
+ - Rakefile
40
+ - lib/generators/status_assignable_patch_generator.rb
41
+ - lib/generators/templates/monkey_patch.rb.erb
42
+ - lib/status_assignable.rb
43
+ - lib/status_assignable/association.rb
44
+ - lib/status_assignable/version.rb
45
+ - status_assignable.gemspec
46
+ homepage: https://github.com/tieeeeen1994/rails-status-assignable
47
+ licenses:
48
+ - MIT
49
+ metadata:
50
+ homepage_uri: https://github.com/tieeeeen1994/rails-status-assignable
51
+ rubygems_mfa_required: 'true'
52
+ post_install_message:
53
+ rdoc_options: []
54
+ require_paths:
55
+ - lib
56
+ required_ruby_version: !ruby/object:Gem::Requirement
57
+ requirements:
58
+ - - ">="
59
+ - !ruby/object:Gem::Version
60
+ version: 3.0.0
61
+ required_rubygems_version: !ruby/object:Gem::Requirement
62
+ requirements:
63
+ - - ">="
64
+ - !ruby/object:Gem::Version
65
+ version: '0'
66
+ requirements: []
67
+ rubygems_version: 3.5.3
68
+ signing_key:
69
+ specification_version: 4
70
+ summary: Allows models to be assigned a status.
71
+ test_files: []