active_record_compose 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: f87118b489cd061b4912c625ec2b9bdc91ad4b024e69cd6a6c45ab9c884018f3
4
+ data.tar.gz: 22eec41668831a5f97d5935502d4c4d61de723b78dd2f70d2dca2bbfb4d9fa52
5
+ SHA512:
6
+ metadata.gz: 180d9e45c2e18dc362d0169a22040759614882e09254c4fc8ad80ead07302c280446cab288c5042f81f33d339ab00b114d888536f691ab817063dc5dc6765cc0
7
+ data.tar.gz: a4ba3164829709bbdbb38f0232b555ef210b6ce0783348317c430ffb9d1931f9b9b48bec3f28fefe757ee9ce6f9c8b3dcfb3a53ec557650eab4d6e7a8870e13f
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,31 @@
1
+ AllCops:
2
+ TargetRubyVersion: 3.1
3
+ NewCops: enable
4
+ SuggestExtensions: false
5
+
6
+ Style/Documentation:
7
+ Enabled: false
8
+
9
+ Style/StringLiterals:
10
+ Enabled: true
11
+
12
+ Style/StringLiteralsInInterpolation:
13
+ Enabled: true
14
+
15
+ Style/SymbolProc:
16
+ Enabled: false
17
+
18
+ Style/TrailingCommaInArguments:
19
+ EnforcedStyleForMultiline: comma
20
+
21
+ Style/TrailingCommaInArrayLiteral:
22
+ EnforcedStyleForMultiline: comma
23
+
24
+ Style/TrailingCommaInHashLiteral:
25
+ EnforcedStyleForMultiline: comma
26
+
27
+ Layout/LineLength:
28
+ Max: 120
29
+
30
+ Metrics/BlockLength:
31
+ Enabled: false
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2023-07-29
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 hamajyotan@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) 2023 SAKAGUCHI Takashi
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,290 @@
1
+ # ActiveRecordCompose
2
+
3
+ activermodel (activerecord) form object pattern.
4
+
5
+ ![CI](https://github.com/hamajyotan/active_record_compose/workflows/CI/badge.svg)
6
+
7
+ ## Installation
8
+
9
+ To install `active_record_compose`, just put this line in your Gemfile:
10
+
11
+ ```ruby
12
+ gem 'active_record_compose'
13
+ ```
14
+
15
+ Then bundle
16
+
17
+ ```sh
18
+ $ bundle
19
+ ```
20
+
21
+ ## Usage
22
+
23
+ ### ActiveRecordCompose::Model basic
24
+
25
+ It wraps AR objects or equivalent models to provide unified operation.
26
+ For example, the following cases are supported
27
+
28
+ #### Context-specific callbacks.
29
+
30
+ A callback is useful to define some processing before or after a save in a particular model.
31
+ However, if a callback is written directly in the AR model, it is necessary to consider the case where the model is updated in other contexts.
32
+ In particular, if you frequently create with test data, previously unnecessary processing will be called at every point of creation.
33
+ In addition to cost, the more complicated the callbacks you write, the more difficult it will be to create even a single test data.
34
+ If the callbacks are written in a class that inherits from `ApplicationRecordCompose::Model`, the AR model itself will not be polluted, and the context can be limited.
35
+
36
+ ```ruby
37
+ class AccountRegistration < ActiveRecordCompose::Model
38
+ def initialize(account = Account.new, attributes = {})
39
+ @account = account
40
+ super(attributes)
41
+
42
+ # By including AR instance in models, AR instance itself is saved when this model is saved.
43
+ models.push(account)
44
+ end
45
+
46
+ # By delegating these to the AR instance,
47
+ # For example, this model itself can be given directly as an argument to form_with, and it will behave as if it were an instance of the model.
48
+ delegate :id, :persisted?, to: :account
49
+
50
+ # Defines an attribute of the same name that delegates to account#name and account#email
51
+ delegate_attribute :name, :email, to: :account
52
+
53
+ # You can only define post-processing if you update through this model.
54
+ # If this is written directly into the AR model, for example, it would be necessary to consider a callback control for each test data generation.
55
+ after_commit :try_send_email_message
56
+
57
+ private
58
+
59
+ attr_reader :account
60
+
61
+ def try_send_email_message
62
+ SendEmailConfirmationJob.perform_later(account)
63
+ end
64
+ end
65
+ ```
66
+
67
+ #### Validation limited to a specific context.
68
+
69
+ Validates are basically fired in all cases where the model is manipulated. To avoid this, use `on: :create`, etc. to make it work only in specific cases.
70
+ and so on to work only in specific cases. This allows you to create context-sensitive validations for the same model operation.
71
+ However, this is the first step in making the model more and more complex. You will have to go around with `update(context: :foo)`
72
+ In some cases, you may have to go around with the context option, such as `update(context: :foo)` everywhere.
73
+ By writing validates in a class that extends `ApplicationRecordCompose::Model`, you can define context-specific validation without polluting the AR model itself.
74
+
75
+ ```ruby
76
+ class AccountRegistration < ActiveRecordCompose::Model
77
+ def initialize(account = Account.new, attributes = {})
78
+ @account = account
79
+ super(attributes)
80
+ models.push(account)
81
+ end
82
+
83
+ delegate :id, :persisted?, to: :account
84
+ delegate_attribute :name, :email, to: :account
85
+
86
+ # Only if this model is used, also check the validity of the domain
87
+ before_validation :require_valid_domain
88
+
89
+ private
90
+
91
+ attr_reader :account
92
+
93
+ # Validity of the domain part of the e-mail address is also checked only when registering an account.
94
+ def require_valid_domain
95
+ e = ValidEmail2::Address.new(email.to_s)
96
+ unless e.valid?
97
+ errors.add(:email, :invalid_format)
98
+ return
99
+ end
100
+ unless e.valid_mx?
101
+ errors.add(:email, :invalid_domain)
102
+ end
103
+ end
104
+ end
105
+ ```
106
+
107
+ ```ruby
108
+ account = Account.new(name: 'new account', email: 'foo@example.com')
109
+ account.valid? #=> true
110
+
111
+ account_registration = AccountRegistration.new(name: 'new account', email: 'foo@example.com')
112
+ account_registration.valid? #=> false
113
+ ```
114
+
115
+ #### updating multiple models at the same time.
116
+
117
+ In an AR model, you can add, for example, `autosave: true` or `accepts_nested_attributes_for` to an association to update the related models at the same time.
118
+ There are ways to update related models at the same time. The operation is safe because it is transactional.
119
+ `ApplicationRecordCompose::Model` has an internal array called models. By adding an AR object to this models array
120
+ By adding an AR object to the models, the object stored in the models provides an atomic update operation via #save.
121
+
122
+ ```ruby
123
+ class AccountRegistration < ActiveRecordCompose::Model
124
+ def initialize(account = Account.new, profile = account.build_profile, attributes = {})
125
+ @account = account
126
+ @profile = profile
127
+ super(attributes)
128
+ models << account << profile
129
+ end
130
+
131
+ delegate :id, :persisted?, to: :account
132
+ delegate_attribute :name, :email, to: :account
133
+ delegate_attribute :firstname, :lastname, :age, to: :profile
134
+
135
+ private
136
+
137
+ attr_reader :account, :profile
138
+ end
139
+ ```
140
+
141
+ ```ruby
142
+ Account.count #=> 0
143
+ Profile.count #=> 0
144
+
145
+ account_registration =
146
+ AccountRegistration.new(
147
+ name: 'foo',
148
+ email: 'foo@example.com',
149
+ firstname: 'bar',
150
+ lastname: 'baz',
151
+ age: 36,
152
+ )
153
+ account_registration.save!
154
+
155
+ Account.count #=> 1
156
+ Profile.count #=> 1
157
+ ```
158
+
159
+ By adding to the `models` array while specifying `context: :destroy`, you can perform a delete instead of a save on the model at `#save` time.
160
+
161
+ ```ruby
162
+ class AccountResignation < ActiveRecordCompose::Model
163
+ def initialize(account)
164
+ @account = account
165
+ @profile = account.profile # Suppose that Account has_one Profile.
166
+ models.push(account)
167
+ models.push(profile, context: :destroy)
168
+ end
169
+
170
+ attr_reader :account, :profile
171
+
172
+ before_save :set_resigned_at
173
+
174
+ private
175
+
176
+ def set_resigned_at
177
+ account.resigned_at = Time.zone.now
178
+ end
179
+ end
180
+ ```
181
+
182
+ ```ruby
183
+ account = Account.last
184
+
185
+ account.resigned_at.present? #=> nil
186
+ account.profile.blank? #=> false
187
+
188
+ account_resignation = AccountResignation.new(account)
189
+ account_resignation.save!
190
+
191
+ account.reload
192
+ account.resigned_at.present? #=> Tue, 02 Jan 2024 22:58:01.991008870 JST +09:00
193
+ account.profile.blank? #=> true
194
+ ```
195
+
196
+ ### `delegate_attribute`
197
+
198
+ It provides a macro description that expresses access to the attributes of the AR model through delegation.
199
+
200
+ ```ruby
201
+ class AccountRegistration < ActiveRecordCompose::Model
202
+ def initialize(account)
203
+ @account = account
204
+ super(attributes)
205
+ models.push(account)
206
+ end
207
+
208
+ attribute :original_attribute, :string, default: 'qux'
209
+ delegate_attribute :name, to: :account
210
+
211
+ private
212
+
213
+ attr_reader :account
214
+ end
215
+ ```
216
+
217
+ ```ruby
218
+ account = Account.new
219
+ account.name = 'foo'
220
+
221
+ registration = AccountRegistration.new(account)
222
+ registration.name #=> 'foo'
223
+
224
+ registration.name = 'bar'
225
+ account.name #=> 'bar'
226
+ ```
227
+
228
+ Overrides `#attributes`, merging attributes defined with `delegate_attribute` in addition to the original attributes.
229
+
230
+ ```
231
+ account.attributes #=> {'original_attribute' => 'qux', 'name' => 'bar'}
232
+ ```
233
+
234
+ ### Callback ordering by `#save`, `#create` and `#update`.
235
+
236
+ Sometimes, multiple AR objects are passed to the models in the arguments.
237
+ It is not strictly possible to distinguish between create and update operations, regardless of the state of `#persisted?`.
238
+ Therefore, control measures such as separating callbacks with `after_create` and `after_update` based on the `#persisted?` of AR objects are left to the discretion of the user,
239
+ rather than being determined by the state of the AR objects themselves.
240
+
241
+ ```ruby
242
+ class ComposedModel < ActiveRecordCompose::Model
243
+ # ...
244
+
245
+ before_save { puts 'before_save called!' }
246
+ before_create { puts 'before_create called!' }
247
+ before_update { puts 'before_update called!' }
248
+ after_save { puts 'after_save called!' }
249
+ after_create { puts 'after_create called!' }
250
+ after_update { puts 'after_update called!' }
251
+ end
252
+ ```
253
+
254
+ ```ruby
255
+ model = ComposedModel.new
256
+
257
+ model.save
258
+ # before_save called!
259
+ # after_save called!
260
+
261
+ model.create
262
+ # before_save called!
263
+ # before_create called!
264
+ # after_create called!
265
+ # after_save called!
266
+
267
+ model.update
268
+ # before_save called!
269
+ # before_update called!
270
+ # after_update called!
271
+ # after_save called!
272
+ ```
273
+
274
+ ## Development
275
+
276
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
277
+
278
+ 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).
279
+
280
+ ## Contributing
281
+
282
+ Bug reports and pull requests are welcome on GitHub at https://github.com/hamajyotan/active_record_compose. 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/hamajyotan/active_record_compose/blob/main/CODE_OF_CONDUCT.md).
283
+
284
+ ## License
285
+
286
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
287
+
288
+ ## Code of Conduct
289
+
290
+ Everyone interacting in the ActiveRecord::Compose project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/hamajyotan/active_record_compose/blob/main/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,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveRecordCompose
4
+ module DelegateAttribute
5
+ extend ActiveSupport::Concern
6
+
7
+ included do
8
+ class_attribute :delegated_attributes, instance_writer: false
9
+ end
10
+
11
+ class_methods do
12
+ def delegate_attribute(*attributes, to:, **options)
13
+ delegates = attributes.flat_map do |attribute|
14
+ reader = attribute
15
+ writer = "#{attribute}="
16
+
17
+ [reader, writer]
18
+ end
19
+
20
+ delegate(*delegates, to:, **options)
21
+ delegated_attributes = (self.delegated_attributes ||= [])
22
+ attributes.each { delegated_attributes.push(_1.to_s) }
23
+ end
24
+ end
25
+
26
+ def attributes
27
+ super.merge(delegated_attributes.to_h { [_1, public_send(_1)] })
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveRecordCompose
4
+ class Error < ::StandardError; end
5
+
6
+ class RecordNotSaved < ::ActiveRecordCompose::Error
7
+ def initialize(message, record)
8
+ super(message)
9
+ @record = record
10
+ end
11
+
12
+ attr_reader :record
13
+ end
14
+ end
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveRecordCompose
4
+ class InnerModel
5
+ def initialize(inner_model, context: :save)
6
+ @inner_model = inner_model
7
+ @context = context
8
+ end
9
+
10
+ delegate :errors, to: :inner_model
11
+
12
+ def context
13
+ @context.respond_to?(:call) ? @context.call(inner_model) : @context
14
+ end
15
+
16
+ def save!
17
+ case context
18
+ when :destroy
19
+ inner_model.destroy!
20
+ else
21
+ inner_model.save!
22
+ end
23
+ end
24
+
25
+ def invalid?
26
+ case context
27
+ when :destroy
28
+ false
29
+ else
30
+ inner_model.invalid?
31
+ end
32
+ end
33
+
34
+ def valid? = !invalid?
35
+
36
+ private
37
+
38
+ attr_reader :inner_model
39
+ end
40
+ end
@@ -0,0 +1,42 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'active_record_compose/inner_model'
4
+
5
+ module ActiveRecordCompose
6
+ class InnerModelCollection
7
+ include Enumerable
8
+
9
+ def initialize
10
+ @inner_models = []
11
+ end
12
+
13
+ def each
14
+ return enum_for(:each) unless block_given?
15
+
16
+ inner_models.each { yield _1 }
17
+ self
18
+ end
19
+
20
+ def <<(inner_model)
21
+ inner_models << wrap(inner_model, context: :save)
22
+ self
23
+ end
24
+
25
+ def push(inner_model, context: :save)
26
+ inner_models << wrap(inner_model, context:)
27
+ self
28
+ end
29
+
30
+ private
31
+
32
+ attr_reader :inner_models
33
+
34
+ def wrap(inner_model, context:)
35
+ if inner_model.is_a?(ActiveRecordCompose::InnerModel)
36
+ inner_model
37
+ else
38
+ ActiveRecordCompose::InnerModel.new(inner_model, context:)
39
+ end
40
+ end
41
+ end
42
+ end
@@ -0,0 +1,79 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'active_record_compose/delegate_attribute'
4
+ require 'active_record_compose/inner_model_collection'
5
+
6
+ module ActiveRecordCompose
7
+ class Model
8
+ include ActiveModel::Model
9
+ include ActiveModel::Validations::Callbacks
10
+ include ActiveModel::Attributes
11
+ include ActiveRecord::Transactions
12
+
13
+ include ActiveRecordCompose::DelegateAttribute
14
+
15
+ class_attribute :error_class_on_save_error, instance_writer: false, default: ActiveRecordCompose::RecordNotSaved
16
+
17
+ define_model_callbacks :save
18
+ define_model_callbacks :create
19
+ define_model_callbacks :update
20
+
21
+ validate :validate_models
22
+
23
+ def initialize(attributes = {})
24
+ super(attributes)
25
+ end
26
+
27
+ def save
28
+ return false if invalid?
29
+
30
+ save_in_transaction { run_callbacks(:save) { save_models } }
31
+ end
32
+
33
+ def save! = save || raise(error_class_on_save_error.new('Failed to save the model.', self))
34
+
35
+ def create(attributes = {})
36
+ assign_attributes(attributes)
37
+ return false if invalid?
38
+
39
+ save_in_transaction { run_callbacks(:save) { run_callbacks(:create) { save_models } } }
40
+ end
41
+
42
+ def create!(attributes = {})
43
+ create(attributes) || raise(error_class_on_save_error.new('Failed to create the model.', self))
44
+ end
45
+
46
+ def update(attributes = {})
47
+ assign_attributes(attributes)
48
+ return false if invalid?
49
+
50
+ save_in_transaction { run_callbacks(:save) { run_callbacks(:update) { save_models } } }
51
+ end
52
+
53
+ def update!(attributes = {})
54
+ update(attributes) || raise(error_class_on_save_error.new('Failed to update the model.', self))
55
+ end
56
+
57
+ private
58
+
59
+ def models = @models ||= ActiveRecordCompose::InnerModelCollection.new
60
+
61
+ def validate_models = models.select { _1.invalid? }.each { errors.merge!(_1) }
62
+
63
+ def save_in_transaction
64
+ run_callbacks(:commit) do
65
+ result = ::ActiveRecord::Base.transaction do
66
+ raise ActiveRecord::Rollback unless yield
67
+
68
+ true
69
+ end
70
+ result.present?
71
+ rescue StandardError
72
+ run_callbacks :rollback
73
+ raise
74
+ end.present?
75
+ end
76
+
77
+ def save_models = models.all? { _1.save! }
78
+ end
79
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveRecordCompose
4
+ VERSION = '0.1.0'
5
+ end
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'active_record'
4
+
5
+ require_relative 'active_record_compose/version'
6
+ require_relative 'active_record_compose/error'
7
+ require_relative 'active_record_compose/inner_model'
8
+ require_relative 'active_record_compose/inner_model_collection'
9
+ require_relative 'active_record_compose/model'
10
+
11
+ module ActiveRecordCompose
12
+ end
metadata ADDED
@@ -0,0 +1,72 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: active_record_compose
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - hamajyotan
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2024-01-06 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: activerecord
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '6.1'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '6.1'
27
+ description: activemodel form object pattern
28
+ email:
29
+ - hamajyotan@gmail.com
30
+ executables: []
31
+ extensions: []
32
+ extra_rdoc_files: []
33
+ files:
34
+ - ".rspec"
35
+ - ".rubocop.yml"
36
+ - CHANGELOG.md
37
+ - CODE_OF_CONDUCT.md
38
+ - LICENSE.txt
39
+ - README.md
40
+ - Rakefile
41
+ - lib/active_record_compose.rb
42
+ - lib/active_record_compose/delegate_attribute.rb
43
+ - lib/active_record_compose/error.rb
44
+ - lib/active_record_compose/inner_model.rb
45
+ - lib/active_record_compose/inner_model_collection.rb
46
+ - lib/active_record_compose/model.rb
47
+ - lib/active_record_compose/version.rb
48
+ homepage: https://github.com/active_record_compose
49
+ licenses:
50
+ - MIT
51
+ metadata:
52
+ rubygems_mfa_required: 'true'
53
+ post_install_message:
54
+ rdoc_options: []
55
+ require_paths:
56
+ - lib
57
+ required_ruby_version: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: 3.1.0
62
+ required_rubygems_version: !ruby/object:Gem::Requirement
63
+ requirements:
64
+ - - ">="
65
+ - !ruby/object:Gem::Version
66
+ version: '0'
67
+ requirements: []
68
+ rubygems_version: 3.4.10
69
+ signing_key:
70
+ specification_version: 4
71
+ summary: activemodel form object pattern
72
+ test_files: []