active_interaction-extras 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
+ SHA1:
3
+ metadata.gz: 73c4e77c2e101656185ad654364e8a4a609fb440
4
+ data.tar.gz: 7d2a25ed77a026f5257a6370f1c52998d716496a
5
+ SHA512:
6
+ metadata.gz: be0a3a10fcafe850259f2955997ee900e5433967242f85ff64ff54f2b4346773f24e4d3306f72113351b6702a51d13bde1c1aac922db2d6a7ef73d4cd4b4d594
7
+ data.tar.gz: f2994d0a85ee3b11c736bcb9384949388f7a1636924da5e7fa4672c124b4df818553a2b666a062a588ebff11bee08f90d949edd1b35ec1ebc90c21103e511059
data/.gitignore ADDED
@@ -0,0 +1,9 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+ Gemfile.lock
data/.rspec ADDED
@@ -0,0 +1 @@
1
+ --require spec_helper
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at antulik@gmail.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ source "https://rubygems.org"
2
+
3
+ git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
4
+
5
+ # Specify your gem's dependencies in active_interaction-extras.gemspec
6
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2018 Anton Katunin
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,218 @@
1
+ # ActiveInteraction::Extras
2
+
3
+ This gem contains the collection of useful extensions to [active_interaction](https://github.com/AaronLasseigne/active_interaction) gem.
4
+
5
+ ## Installation
6
+
7
+ ```ruby
8
+ gem 'active_interaction-extras'
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ### All
14
+
15
+ ```ruby
16
+ class ApplicationInteraction < ActiveInteraction::Base
17
+ include ActiveInteraction::Extras::All
18
+ # same as
19
+ # include ActiveInteraction::Extras::ActiveJob
20
+ # include ActiveInteraction::Extras::Halt
21
+ # include ActiveInteraction::Extras::ModelFields
22
+ # include ActiveInteraction::Extras::RunCallback
23
+ # include ActiveInteraction::Extras::StrongParams
24
+ # include ActiveInteraction::Extras::Transaction
25
+ end
26
+ ```
27
+
28
+ ### ActiveJob
29
+
30
+ ```ruby
31
+ class ApplicationInteraction < ActiveInteraction::Base
32
+ include ActiveInteraction::Extras::ActiveJob
33
+
34
+ class Job < ActiveJob::Base
35
+ include ActiveInteraction::Extras::ActiveJob::Perform
36
+ end
37
+ end
38
+
39
+ class DoubleService < ApplicationInteraction
40
+ integer :x
41
+
42
+ def execute
43
+ x + x
44
+ end
45
+ end
46
+
47
+ DoubleService.delay.run(x: 2) # queues to run in background
48
+ ```
49
+
50
+ ### Halt
51
+
52
+ ```ruby
53
+ class Service < ActiveInteraction::Base
54
+ include ActiveInteraction::Extras::Halt
55
+
56
+ def execute
57
+ other_method
58
+ puts('finished') # this won't be called
59
+ end
60
+
61
+ def other_method
62
+ errors.add :base, :invalid
63
+ halt! if errors.any?
64
+ # or
65
+ halt_if_errors!
66
+ end
67
+ end
68
+ ```
69
+
70
+ ### ModelFields
71
+
72
+ ```ruby
73
+ class UserForm < ActiveInteraction::Base
74
+ include ActiveInteraction::Extras::ModelFields
75
+
76
+ interface :user
77
+
78
+ model_fields(:user) do
79
+ string :first_name
80
+ string :last_name
81
+ end
82
+
83
+ def execute
84
+ model_fields(:user) # => {:first_name=>"Albert", :last_name=>"Balk"}
85
+ any_changed?(:first_name, :last_name) # => true
86
+ given_model_fields(:user) # => {:first_name=>"Albert"}
87
+ changed_model_fields(:user) # => {:first_name=>"Albert"}
88
+ end
89
+ end
90
+
91
+ user = OpenStruct.new(first_name: 'Sam', last_name: 'Balk')
92
+
93
+ UserForm.new(user: user).first_name # => 'Sam'
94
+ UserForm.run!(user: user, first_name: 'Albert')
95
+ ```
96
+
97
+ ### RunCallback
98
+
99
+ ```ruby
100
+ class Service < ActiveInteraction::Base
101
+ include ActiveInteraction::Extras::RunCallback
102
+
103
+ after_run do
104
+ # LogAttempt.log
105
+ end
106
+
107
+ after_successful_run do
108
+ # Email.deliver
109
+ end
110
+
111
+ after_failed_run do
112
+ # NotifyAdminEmail.deliver
113
+ end
114
+
115
+ def execute
116
+ end
117
+ end
118
+ ```
119
+
120
+ ### StrongParams
121
+
122
+
123
+ ```ruby
124
+ class UpdateUserForm < ActiveInteraction::Base
125
+ include ActiveInteraction::Extras::StrongParams
126
+
127
+ string :first_name, default: nil, permit: true
128
+ string :last_name, default: nil
129
+
130
+ def execute
131
+ first_name # => 'Allowed'
132
+ last_name # => nil
133
+ end
134
+ end
135
+
136
+ UpdateUserForm.new.to_model.model_name.param_key # => 'update_user_form'
137
+
138
+ form_params = ActionController::Parameters.new(
139
+ update_user_form: {
140
+ first_name: 'Allowed',
141
+ last_name: 'Not allowed',
142
+ },
143
+ )
144
+
145
+ Service.run(params: form_params)
146
+ ```
147
+
148
+ ### Transaction
149
+
150
+ ```ruby
151
+ class UpdateUserForm < ActiveInteraction::Base
152
+ include ActiveInteraction::Extras::Transaction
153
+
154
+ run_in_transaction!
155
+
156
+ def execute
157
+ Comment.create! # succeeds
158
+
159
+ errors.add(:base, :invalid)
160
+ end
161
+ end
162
+
163
+ UpdateUserForm.run
164
+ Comment.count # => 0
165
+ ```
166
+
167
+ ### Rspec
168
+
169
+ ```ruby
170
+ class SomeService < ActiveInteraction::Base
171
+ integer :x
172
+ end
173
+
174
+ RSpec.describe SomeService do
175
+ include ActiveInteraction::Extras::Rspec
176
+
177
+ it 'works' do
178
+ expect_to_execute(SomeService,
179
+ with: [{ x: 1 }]
180
+ return: :asd
181
+ )
182
+
183
+ result = SomeService.run! x: 1
184
+
185
+ expect(result).to eq :asd
186
+ end
187
+
188
+ it 'lists all mocks' do
189
+ # allow_to_run
190
+ # allow_to_execute
191
+ # allow_to_delay_run
192
+ # allow_to_delay_execute
193
+
194
+ # expect_to_run / expect_not_to_run / expect_to_not_run
195
+ # expect_to_execute
196
+ # expect_to_delay_run / expect_to_not_run_delayed
197
+ # expect_to_delay_execute
198
+ end
199
+ end
200
+ ```
201
+
202
+ ## Development
203
+
204
+ After checking out the repo, run `bin/setup` to install dependencies. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
205
+
206
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
207
+
208
+ ## Contributing
209
+
210
+ Bug reports and pull requests are welcome on GitHub at https://github.com/antulik/active_interaction-extras. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
211
+
212
+ ## License
213
+
214
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
215
+
216
+ ## Code of Conduct
217
+
218
+ Everyone interacting in the ActiveInteraction::Extras project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/antulik/active_interaction-extras/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,2 @@
1
+ require "bundler/gem_tasks"
2
+ task :default => :spec
@@ -0,0 +1,31 @@
1
+
2
+ lib = File.expand_path("../lib", __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require "active_interaction/extras/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "active_interaction-extras"
8
+ spec.version = ActiveInteraction::Extras::VERSION
9
+ spec.authors = ["Anton Katunin"]
10
+ spec.email = ["antulik@gmail.com"]
11
+
12
+ spec.summary = %q{Extension for active_interaction gem}
13
+ spec.description = %q{Extension for active_interaction gem}
14
+ spec.homepage = "https://github.com/antulik/xxxx"
15
+ spec.license = "MIT"
16
+
17
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
18
+ f.match(%r{^(test|spec|features)/})
19
+ end
20
+ spec.bindir = "exe"
21
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
22
+ spec.require_paths = ["lib"]
23
+
24
+ spec.add_dependency "active_interaction", ">= 3.0.0"
25
+ spec.add_dependency "active_interaction-active_job", ">= 0"
26
+ spec.add_development_dependency "bundler", "~> 1.16"
27
+ spec.add_development_dependency "rake", "~> 10.0"
28
+ spec.add_development_dependency "rspec", "~> 3.7"
29
+ spec.add_development_dependency "rails", ">= 4.0"
30
+ spec.add_development_dependency "pry"
31
+ end
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "active_interaction/extras"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,11 @@
1
+ module ActiveInteraction::Extras::ActiveJob
2
+ extend ActiveSupport::Concern
3
+
4
+ include ActiveInteraction::ActiveJob::Core
5
+
6
+ module Perform
7
+ extend ActiveSupport::Concern
8
+
9
+ include ActiveInteraction::ActiveJob::JobHelper
10
+ end
11
+ end
@@ -0,0 +1,10 @@
1
+ module ActiveInteraction::Extras::All
2
+ extend ActiveSupport::Concern
3
+
4
+ include ActiveInteraction::Extras::ActiveJob
5
+ include ActiveInteraction::Extras::Halt
6
+ include ActiveInteraction::Extras::ModelFields
7
+ include ActiveInteraction::Extras::RunCallback
8
+ include ActiveInteraction::Extras::StrongParams
9
+ include ActiveInteraction::Extras::Transaction
10
+ end
@@ -0,0 +1,19 @@
1
+ module ActiveInteraction::Extras::Halt
2
+ extend ActiveSupport::Concern
3
+
4
+ included do
5
+ set_callback :execute, :around, lambda { |_interaction, block|
6
+ catch :strict_error do
7
+ block.call
8
+ end
9
+ }
10
+ end
11
+
12
+ def halt!
13
+ throw :strict_error, errors
14
+ end
15
+
16
+ def halt_if_errors!
17
+ halt! if errors.any?
18
+ end
19
+ end
@@ -0,0 +1,122 @@
1
+ module ActiveInteraction::Extras::ModelFields
2
+ extend ActiveSupport::Concern
3
+
4
+ # returns hash of all model fields and their values
5
+ def model_fields(model_name)
6
+ fields = self.class.model_field_cache[model_name]
7
+ inputs.slice(*fields)
8
+ end
9
+
10
+ # returns hash of only changed model fields and their values
11
+ def changed_model_fields(model_name)
12
+ model_fields(model_name).select do |field, _value|
13
+ any_changed?(field)
14
+ end
15
+ end
16
+
17
+ # returns hash of only given model fields and their values
18
+ def given_model_fields(model_name)
19
+ model_fields(model_name).select do |field, _value|
20
+ given?(field)
21
+ end
22
+ end
23
+
24
+ class Context < SimpleDelegator
25
+ attr_accessor :from_model_name
26
+ attr_accessor :model_field_cache
27
+
28
+ def custom_filter_attribute(name, opts = {})
29
+ from_model_name = self.from_model_name
30
+ model_field_cache[from_model_name] = model_field_cache[from_model_name] << name
31
+
32
+ __getobj__.send __callee__, name, opts
33
+ end
34
+
35
+ alias interface custom_filter_attribute
36
+ alias date custom_filter_attribute
37
+ alias time custom_filter_attribute
38
+ alias date_time custom_filter_attribute
39
+ alias integer custom_filter_attribute
40
+ alias decimal custom_filter_attribute
41
+ alias float custom_filter_attribute
42
+ alias string custom_filter_attribute
43
+ alias symbol custom_filter_attribute
44
+ alias object custom_filter_attribute
45
+ alias hash custom_filter_attribute
46
+ alias file custom_filter_attribute
47
+ alias boolean custom_filter_attribute
48
+ alias array custom_filter_attribute
49
+ end
50
+
51
+ # checks if value was given to the service and the value is different from
52
+ # the one on the model
53
+ def any_changed?(*fields)
54
+ fields.any? do |field|
55
+ model_field = self.class.model_field_cache_inverse[field]
56
+ value_changed = true
57
+
58
+ if model_field
59
+ value_changed = send(model_field).send(field) != send(field)
60
+ end
61
+
62
+ given?(field) && value_changed
63
+ end
64
+ end
65
+
66
+ # overwritten to pre-populate model fields
67
+ def populate_filters(_inputs)
68
+ super.tap do
69
+ self.class.filters.each do |name, filter|
70
+ next if given?(name)
71
+
72
+ model_field = self.class.model_field_cache_inverse[name]
73
+ next if model_field.nil?
74
+
75
+ value = public_send(model_field)&.public_send(name)
76
+ public_send("#{name}=", filter.clean(value, self))
77
+ end
78
+ end
79
+ end
80
+
81
+ class_methods do
82
+ def model_field_cache
83
+ @model_field_cache ||= Hash.new { [] }
84
+ end
85
+
86
+ def model_field_cache_inverse
87
+ @model_field_cache_inverse ||= model_field_cache.each_with_object({}) do |(model, fields), result|
88
+ fields.each do |field|
89
+ result[field] = model
90
+ end
91
+ end
92
+ end
93
+
94
+ # Default values from the model in the other field
95
+ #
96
+ # object :user
97
+ # model_fields(:user) do
98
+ # string :first_name
99
+ # string :last_name
100
+ # end
101
+ #
102
+ # >> interaction.new(user: User.new(first_name: 'John')).first_name
103
+ # => 'John'
104
+ #
105
+ def model_fields(model_name, opts = {}, &block)
106
+ if block
107
+ ref_model_field_cache = model_field_cache
108
+ opts.reverse_merge!(default: nil, permit: true)
109
+
110
+ with_options opts do
111
+ context = Context.new(self)
112
+ context.from_model_name = model_name
113
+ context.model_field_cache = ref_model_field_cache
114
+
115
+ context.instance_exec(&block)
116
+ end
117
+ end
118
+
119
+ model_field_cache[model_name]
120
+ end
121
+ end
122
+ end
@@ -0,0 +1,238 @@
1
+ module ActiveInteraction::Extras::Rspec
2
+ # Helper method to stub service objects in unit tests, while verifying
3
+ # that they are called with valid arguments.
4
+ #
5
+ # This stub does NOT run after_run callbacks.
6
+ #
7
+ # @param [Class] klass Service class to stub
8
+ #
9
+ # @param [Hash] opts
10
+ # @option opts [Boolean] :fail (false) If execution should add error
11
+ # @option opts (see Rspec::Mocks::MessageExpectation#with) :with (any_args)
12
+ # Inputs for the service
13
+ # @option opts (void) :return (nil) Execution return value
14
+ # @option opts (void) :execute (Proc) Execution proc
15
+ #
16
+ # @example Simple stub
17
+ # expect_to_execute(X)
18
+ #
19
+ # @example With all arguments
20
+ # expect_to_execute(X, with: hash_including(:key), return: 1, fail: false)
21
+ #
22
+ # @return [void]
23
+ #
24
+ def expect_to_execute(klass, opts = {})
25
+ stub_service_execute(:expect, klass, opts)
26
+ end
27
+
28
+ # @see #expect_to_execute
29
+ def allow_to_execute(klass, opts = {})
30
+ stub_service_execute(:allow, klass, opts)
31
+ end
32
+
33
+ # Stub service run method. Does not validate inputs
34
+ #
35
+ # @see #expect_to_execute
36
+ def expect_to_run(klass, opts = {})
37
+ stub_service_run(:expect, klass, opts)
38
+ end
39
+
40
+ # @see #expect_to_run
41
+ def allow_to_run(klass, opts = {})
42
+ stub_service_run(:allow, klass, opts)
43
+ end
44
+
45
+ # Make sure the service is not initialized
46
+ #
47
+ # @param [Class] klass Service class to stub
48
+ #
49
+ # @param [Hash] opts
50
+ # @option opts (see Rspec::Mocks::MessageExpectation#with) :with (any_args)
51
+ # Inputs for the service
52
+ #
53
+ def expect_not_to_run(klass, opts = {})
54
+ alias_new_method(klass)
55
+ with = service_parse_with_option(opts)
56
+
57
+ expect(klass).to_not receive(:new).with(*with)
58
+ end
59
+
60
+ alias expect_to_not_run expect_not_to_run
61
+
62
+ def expect_to_not_run_delayed(klass, opts = {})
63
+ alias_delay_method(klass)
64
+
65
+ with = service_parse_job_with_option(opts)
66
+
67
+ expect(klass).to_not receive(:delay).with(*with)
68
+ end
69
+
70
+ # see expect_to_run
71
+ #
72
+ # additional params
73
+ #
74
+ # @option opts (see Rspec::Mocks::MessageExpectation#with) :with_job (any_args)
75
+ # queueing params for the job
76
+ #
77
+ def expect_to_delay_run(klass, opts = {})
78
+ stub_service_delay :expect, :expect_to_run, klass, opts
79
+ end
80
+
81
+ # see expect_to_execute
82
+ # same but for the .delay and background queueing
83
+ #
84
+ # additional params
85
+ #
86
+ # @option opts (see Rspec::Mocks::MessageExpectation#with) :with_job (any_args)
87
+ # queueing params for the job
88
+ #
89
+ def expect_to_delay_execute(klass, opts = {})
90
+ stub_service_delay :expect, :expect_to_execute, klass, opts
91
+ end
92
+
93
+ # see allow_to_run
94
+ #
95
+ # additional params
96
+ #
97
+ # @option opts (see Rspec::Mocks::MessageExpectation#with) :with_job (any_args)
98
+ # queueing params for the job
99
+ #
100
+ def allow_to_delay_run(klass, opts = {})
101
+ stub_service_delay :allow, :allow_to_run, klass, opts
102
+ end
103
+
104
+ # see allow_to_execute
105
+ #
106
+ # additional params
107
+ #
108
+ # @option opts (see Rspec::Mocks::MessageExpectation#with) :with_job (any_args)
109
+ # queueing params for the job
110
+ #
111
+ def allow_to_delay_execute(klass, opts = {})
112
+ stub_service_delay :allow, :allow_to_execute, klass, opts
113
+ end
114
+
115
+ # @private
116
+ def stub_service_delay(expectation, expect_helper, klass, opts)
117
+ alias_delay_method(klass)
118
+
119
+ with = service_parse_job_with_option(opts)
120
+
121
+ send(expectation, klass).to(
122
+ # ^^^^^
123
+ # If failed here, the .delay method was not called
124
+ # or called with invalid arguments
125
+ #
126
+ receive(:delay).with(*with) do |*args|
127
+ # get the original .delay return value
128
+ delayed_run = klass.original_delay(*args)
129
+
130
+ opts[:execute] ||= proc do |instance|
131
+ # call original queueing logic, so the argument serialisation is triggered
132
+ delayed_run.run(instance.raw_inputs)
133
+ end
134
+
135
+ send(expect_helper, klass, opts)
136
+ klass
137
+ end,
138
+ )
139
+ end
140
+
141
+ # @private
142
+ def stub_service_run(expectation, klass, opts)
143
+ stub_service_validate_opts opts
144
+ alias_new_method(klass)
145
+ with = service_parse_with_option(opts)
146
+
147
+ send(expectation, klass).to(
148
+ # ^^^^^^^^^^^^^^^^^^^^^^^^
149
+ # If failed here, the service did not run
150
+ #
151
+ receive(:new).with(*with) do |*args|
152
+ instance = klass.original_new(*args)
153
+ send(expectation, instance).to receive(:run) do
154
+ instance.errors.add :base, 'forced test failure' if opts[:fail]
155
+
156
+ instance.result =
157
+ if opts[:execute].respond_to? :call
158
+ opts[:execute].call(instance)
159
+ else
160
+ opts[:return]
161
+ end
162
+
163
+ instance
164
+ end
165
+ instance
166
+ end,
167
+ )
168
+ end
169
+
170
+ # @private
171
+ def stub_service_execute(expectation, klass, opts)
172
+ stub_service_validate_opts opts
173
+ alias_new_method(klass)
174
+ with = service_parse_with_option(opts)
175
+
176
+ # TODO: change so rspec displays correct message
177
+ send(expectation, klass).to(
178
+ # ^^^^^^^^^^^^^^^^^^^^^^^
179
+ # If failed here, the service was not called
180
+ #
181
+ receive(:new).with(*with) do |*args|
182
+ instance = klass.original_new(*args)
183
+ instance.disable_after_run_callback
184
+ send(expectation, instance).to(
185
+ #
186
+ # If failed here, the service was called, but failed because it's invalid
187
+ #
188
+ receive(:execute) do
189
+ instance.errors.add :base, 'forced test failure' if opts[:fail]
190
+
191
+ if opts[:execute].respond_to? :call
192
+ opts[:execute].call(instance)
193
+ else
194
+ opts[:return]
195
+ end
196
+ end,
197
+ )
198
+
199
+ instance
200
+ end,
201
+ )
202
+ end
203
+
204
+ # @private
205
+ def alias_new_method(klass)
206
+ return if klass.respond_to?(:original_new)
207
+
208
+ klass.define_singleton_method :original_new, &klass.method(:new)
209
+ end
210
+
211
+ # @private
212
+ def alias_delay_method(klass)
213
+ return if klass.respond_to?(:original_delay)
214
+
215
+ klass.define_singleton_method :original_delay, &klass.method(:delay)
216
+ end
217
+
218
+ # @private
219
+ def service_parse_with_option(opts)
220
+ with = opts.fetch(:with, [any_args])
221
+ with = [with] unless with.is_a? Array
222
+ with
223
+ end
224
+
225
+ def service_parse_job_with_option(opts)
226
+ with_opts = {}
227
+ with_opts[:with] = opts.delete(:job_with) if opts.key? :job_with
228
+ service_parse_with_option(with_opts)
229
+ end
230
+
231
+ # @private
232
+ def stub_service_validate_opts(opts)
233
+ raise ArgumentError, 'Pick one :return or :execute, but not both' if opts.key?(:return) && opts.key?(:execute)
234
+
235
+ invalid_keys = opts.except(:fail, :return, :with, :execute).keys
236
+ raise ArgumentError, 'Unknown options: ' + invalid_keys.to_s if invalid_keys.any?
237
+ end
238
+ end
@@ -0,0 +1,55 @@
1
+ module ActiveInteraction::Extras::RunCallback
2
+ extend ActiveSupport::Concern
3
+
4
+ included do
5
+ define_callbacks :run
6
+ end
7
+
8
+ def run
9
+ run_callbacks(:run) do
10
+ super
11
+ end
12
+ end
13
+
14
+ def after_run_callback_enabled?
15
+ !@after_run_callback_disabled
16
+ end
17
+
18
+ def enable_after_run_callback
19
+ @after_run_callback_disabled = false
20
+ end
21
+
22
+ # This is useful for testing
23
+ def disable_after_run_callback
24
+ @after_run_callback_disabled = true
25
+ end
26
+
27
+ class_methods do
28
+ # Run callback is executed outside transaction if transaction is used.
29
+ # Make sure code in after_run hook can't fail, so preferably only run async code here
30
+ def after_run(*args, &block)
31
+ opts = args.extract_options!
32
+ opts[:if] = [:after_run_callback_enabled?] + Array(opts[:if])
33
+
34
+ set_callback :run, :after, *args, opts, &block
35
+ end
36
+
37
+ # See #after_run
38
+ # only runs when service has successfully finished and outcome is valid
39
+ def after_successful_run(*args, &block)
40
+ opts = args.extract_options!
41
+ opts[:if] = [:valid?, :after_run_callback_enabled?] + Array(opts[:if])
42
+
43
+ set_callback :run, :after, *args, opts, &block
44
+ end
45
+
46
+ # See #after_run
47
+ def after_failed_run(*args, &block)
48
+ opts = args.extract_options!
49
+ opts[:if] = [:after_run_callback_enabled?] + Array(opts[:if])
50
+ opts[:unless] = [:valid?] + Array(opts[:unless])
51
+
52
+ set_callback :run, :after, *args, opts, &block
53
+ end
54
+ end
55
+ end
@@ -0,0 +1,44 @@
1
+ module ActiveInteraction::Extras::StrongParams
2
+ extend ActiveSupport::Concern
3
+
4
+ def process_inputs(inputs)
5
+ # TODO: whitelist :params and :form_params, so they could not be used as filters
6
+ return super if self.class.filters.key?(:params) || self.class.filters.key?(:form_params)
7
+
8
+ if inputs.key?(:params) && inputs.key?(:form_params)
9
+ raise ArgumentError, 'Both options :params and :form_params are given. ' \
10
+ 'One or none are accepted.'
11
+ end
12
+
13
+ form_params = inputs.fetch(:form_params) do
14
+ params = inputs[:params]
15
+ if params
16
+ key = to_model&.model_name&.param_key
17
+ params.require(key) if params.respond_to?(:require) && params.key?(key)
18
+ end
19
+ end
20
+
21
+ if form_params
22
+ inputs = inputs.merge(form_params.permit(self.class.permitted_params))
23
+ end
24
+
25
+ super(inputs)
26
+ end
27
+
28
+ class_methods do
29
+ def permitted_params
30
+ filters.map do |filter_name, filter|
31
+ next unless filter.options[:permit]
32
+
33
+ case filter
34
+ when ActiveInteraction::ArrayFilter
35
+ { filter_name => [] }
36
+ when ActiveInteraction::HashFilter
37
+ { filter_name => {} }
38
+ else
39
+ filter_name
40
+ end
41
+ end.compact
42
+ end
43
+ end
44
+ end
@@ -0,0 +1,32 @@
1
+ module ActiveInteraction::Extras::Transaction
2
+ extend ActiveSupport::Concern
3
+
4
+ def run_in_transaction!
5
+ result_or_errors = nil
6
+ ActiveRecord::Base.transaction do
7
+ result_or_errors = yield
8
+
9
+ # check by class because
10
+ # errors added by compose method are merged after execute,
11
+ # so we need to check return type ourselves
12
+ #
13
+ # see ActiveInteraction::Runnable#run
14
+ if result_or_errors.is_a?(ActiveInteraction::Errors) && result_or_errors.any?
15
+ raise ActiveRecord::Rollback
16
+ end
17
+
18
+ raise ActiveRecord::Rollback if errors.any?
19
+ end
20
+ result_or_errors
21
+ end
22
+
23
+ class_methods do
24
+ def run_in_transaction!
25
+ set_callback :execute, :around, :run_in_transaction!, prepend: true
26
+ end
27
+
28
+ def skip_run_in_transaction!
29
+ skip_callback :execute, :around, :run_in_transaction!
30
+ end
31
+ end
32
+ end
@@ -0,0 +1,5 @@
1
+ module ActiveInteraction
2
+ module Extras
3
+ VERSION = "0.1.0"
4
+ end
5
+ end
@@ -0,0 +1,18 @@
1
+ require "active_interaction/extras/version"
2
+
3
+ require 'active_support'
4
+ require 'active_interaction'
5
+
6
+ module ActiveInteraction
7
+ module Extras
8
+
9
+ autoload(:ActiveJob, "active_interaction/extras/active_job")
10
+ autoload(:All, "active_interaction/extras/all")
11
+ autoload(:Halt, "active_interaction/extras/halt")
12
+ autoload(:ModelFields, "active_interaction/extras/model_fields")
13
+ autoload(:Rspec, "active_interaction/extras/rspec")
14
+ autoload(:RunCallback, "active_interaction/extras/run_callback")
15
+ autoload(:StrongParams, "active_interaction/extras/strong_params")
16
+ autoload(:Transaction, "active_interaction/extras/transaction")
17
+ end
18
+ end
metadata ADDED
@@ -0,0 +1,162 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: active_interaction-extras
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Anton Katunin
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2018-05-25 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: active_interaction
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: 3.0.0
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: 3.0.0
27
+ - !ruby/object:Gem::Dependency
28
+ name: active_interaction-active_job
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: bundler
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '1.16'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '1.16'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rake
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '10.0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '10.0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: rspec
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '3.7'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '3.7'
83
+ - !ruby/object:Gem::Dependency
84
+ name: rails
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - ">="
88
+ - !ruby/object:Gem::Version
89
+ version: '4.0'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - ">="
95
+ - !ruby/object:Gem::Version
96
+ version: '4.0'
97
+ - !ruby/object:Gem::Dependency
98
+ name: pry
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - ">="
102
+ - !ruby/object:Gem::Version
103
+ version: '0'
104
+ type: :development
105
+ prerelease: false
106
+ version_requirements: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - ">="
109
+ - !ruby/object:Gem::Version
110
+ version: '0'
111
+ description: Extension for active_interaction gem
112
+ email:
113
+ - antulik@gmail.com
114
+ executables: []
115
+ extensions: []
116
+ extra_rdoc_files: []
117
+ files:
118
+ - ".gitignore"
119
+ - ".rspec"
120
+ - CODE_OF_CONDUCT.md
121
+ - Gemfile
122
+ - LICENSE.txt
123
+ - README.md
124
+ - Rakefile
125
+ - active_interaction-extras.gemspec
126
+ - bin/console
127
+ - bin/setup
128
+ - lib/active_interaction/extras.rb
129
+ - lib/active_interaction/extras/active_job.rb
130
+ - lib/active_interaction/extras/all.rb
131
+ - lib/active_interaction/extras/halt.rb
132
+ - lib/active_interaction/extras/model_fields.rb
133
+ - lib/active_interaction/extras/rspec.rb
134
+ - lib/active_interaction/extras/run_callback.rb
135
+ - lib/active_interaction/extras/strong_params.rb
136
+ - lib/active_interaction/extras/transaction.rb
137
+ - lib/active_interaction/extras/version.rb
138
+ homepage: https://github.com/antulik/xxxx
139
+ licenses:
140
+ - MIT
141
+ metadata: {}
142
+ post_install_message:
143
+ rdoc_options: []
144
+ require_paths:
145
+ - lib
146
+ required_ruby_version: !ruby/object:Gem::Requirement
147
+ requirements:
148
+ - - ">="
149
+ - !ruby/object:Gem::Version
150
+ version: '0'
151
+ required_rubygems_version: !ruby/object:Gem::Requirement
152
+ requirements:
153
+ - - ">="
154
+ - !ruby/object:Gem::Version
155
+ version: '0'
156
+ requirements: []
157
+ rubyforge_project:
158
+ rubygems_version: 2.6.8
159
+ signing_key:
160
+ specification_version: 4
161
+ summary: Extension for active_interaction gem
162
+ test_files: []