mime_actor 1.0.1 → 1.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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 45acf30e67a036d73b11bc6f79600212ebf2c69127e2727198e7f0c4a01e8530
4
- data.tar.gz: 43d12c88f6eaf61bc02a34bce84249dd91581d2688f6e05d453f0e532bf1bf5e
3
+ metadata.gz: 7e356a269b89d4a885a52eb435237038188d4fc31187184127c732b1208c3b84
4
+ data.tar.gz: cd49e1dbfa60cf07458fabb1d4681014346d55e4ecb10103d0965ff5d17700a6
5
5
  SHA512:
6
- metadata.gz: 2798078282a7aca6e3af70cd448f7f37a0bf75450429cd3566f0c8f399c9c768805f7dc84de00be386454db9851a182974cd80904c40e875760453682cd4bbe5
7
- data.tar.gz: 359066bc2b07af9d6c5f42ca21762c5b57496aea7f28a0dd28384ec1d5889bc50500a422f8c97db70cbf97a7d727e899ee2ec84b1966bb8ca43882ca33dc135a
6
+ metadata.gz: 6da4591d4873105e14aa60f6911f3d2a216d25c322ba4b437487372e809bb83ea8dbde3dc0eb9cf87cd940bc125d85dfbad7971008a644e69828440b8babf315
7
+ data.tar.gz: b09578b98297808014359ca23f622ee93a0f2ac627446a95f53db2bfca2b6993c87872ee1436535041846771d9cf8f68693470e4be5e7db9eda23f19154a2072
data/COMPARE.md CHANGED
@@ -1,6 +1,6 @@
1
1
  ## Comparison in Rails
2
2
 
3
- When some actions render more than a single MIME type with error handling sfor different MIME type.
3
+ When some actions render more than a single MIME type with error handling for different MIME type.
4
4
  ```rb
5
5
  class EventsController < ActionController::Base
6
6
  def show
@@ -14,7 +14,7 @@ class EventsController < ActionController::Base
14
14
  def create
15
15
  respond_to do |format|
16
16
  format.html do
17
- create_event ? redirect_to "/events/#{@event.id}" : render "create"
17
+ create_event ? redirect_to("/events/#{@event.id}") : render("create")
18
18
  end
19
19
  format.json do
20
20
  create_event!
@@ -31,7 +31,7 @@ class EventsController < ActionController::Base
31
31
  success = update_event
32
32
 
33
33
  respond_to do |format|
34
- format.html { success ? redirect_to "/events/#{@event.id}" : render "update" }
34
+ format.html { success ? redirect_to("/events/#{@event.id}") : render("update") }
35
35
  format.json { render_event_json }
36
36
  end
37
37
  end
@@ -75,16 +75,15 @@ end
75
75
  class EventsController < ActionController::Base
76
76
  include MimeActor::Action
77
77
 
78
- act_before -> { @events = Event.all }, action: :index
78
+ act_before -> { @event_categories = EventCategory.all }, action: :index, format: :html
79
79
 
80
- # dynamically defines the action method according to on: argument
81
80
  act_on_action :index, format: %i[html json]
82
81
 
83
82
  act_after :render_index_html, action: :index, format: :html
84
83
  act_after -> { render json: @events }, action: :index, format: :json
85
84
 
86
85
  def index
87
- @event_categories = EventCategory.all
86
+ @events = Event.all
88
87
  end
89
88
 
90
89
  def render_index_html
@@ -99,7 +98,7 @@ end
99
98
  #### before
100
99
  ```rb
101
100
  class EventsController < ActionController::Base
102
- before_action :load_event, action: %i[show update]
101
+ before_action :load_event, only: %i[show update]
103
102
 
104
103
  rescue_from ActiveRecord::RecordNotFound do |ex|
105
104
  case action_name.to_s
@@ -147,17 +146,17 @@ class EventsController < ActionController::Base
147
146
 
148
147
  act_before :load_event, action: %i[show update]
149
148
 
150
- act_on_action :show, :update, format: :html
151
- act_on_action :show, :update, format: :json, with: -> { render json: @event } # render json using #as_json
149
+ act_on_action :show, :update, format: %i[html json]
152
150
 
153
151
  act_after :render_show_html, action: :show, format: :html
154
152
  act_after :redirect_to_show, action: :update, format: :html
153
+ act_after -> { render json: @event }, format: :json # render json using #as_json
155
154
 
156
155
  rescue_act_from ActiveRecord::RecordNotFound, format: :json, with: :handle_json_error
157
156
  rescue_act_from ActiveRecord::RecordNotFound, format: :html, action: :show do
158
157
  redirect_to events_path
159
158
  end
160
- rescue_act_from ActiveRecord::RecrodNotSaved, format: :html, action: :update, with: -> { render :edit }
159
+ rescue_act_from ActiveRecord::RecordNotSaved, format: :html, action: :update, with: -> { render :edit }
161
160
 
162
161
  def show
163
162
  # ...
@@ -169,6 +168,10 @@ class EventsController < ActionController::Base
169
168
 
170
169
  private
171
170
 
171
+ def load_event
172
+ @event = Event.find(params.require(:event_id))
173
+ end
174
+
172
175
  def render_show_html
173
176
  render :show # render html using @event
174
177
  end
@@ -181,4 +184,4 @@ class EventsController < ActionController::Base
181
184
  render status: :bad_request, json: { error: error.message }
182
185
  end
183
186
  end
184
- ```
187
+ ```
data/README.md CHANGED
@@ -3,7 +3,6 @@
3
3
  [![Version][rubygems_badge]][rubygems]
4
4
  [![CI][ci_badge]][ci_workflows]
5
5
  [![Coverage][coverage_badge]][coverage]
6
- [![Maintainability][maintainability_badge]][maintainability]
7
6
 
8
7
  Action processing with Callback + Rescue handlers for different MIME types in Rails.
9
8
 
@@ -28,6 +27,13 @@ However, it can be a litte bit messy when some actions render more than a single
28
27
 
29
28
  ## Usage
30
29
 
30
+ Include `MimeActor::Action` in the controller, the examples below are written in its class body:
31
+ ```rb
32
+ class EventsController < ActionController::Base
33
+ include MimeActor::Action
34
+ end
35
+ ```
36
+
31
37
  **Mime Actor** allows you to do something like:
32
38
 
33
39
  #### Customize Action for certain MIME type
@@ -108,15 +114,31 @@ The above is equivalent to the following:
108
114
  end
109
115
  ```
110
116
 
117
+ #### Tagging logs with the Action + MIME type
118
+ ```rb
119
+ act_around :tag_act_logs
120
+
121
+ def tag_act_logs
122
+ return yield unless logger.respond_to?(:push_tags)
123
+
124
+ tags = [act_action, act_format]
125
+ logger.push_tags(*tags)
126
+ yield
127
+ ensure
128
+ logger.pop_tags(tags.size) if tags
129
+ end
130
+ ```
131
+ NOTE: avoid `logger.tagged { ... }` here, on Rails 7.1 to 8.1 a broadcast logger yields once per logger, running the act again.
132
+
111
133
  #### Rescue handler registration for certain Action + MIME type
112
134
  ```rb
113
135
  act_before :load_event, action: %i[show update]
114
136
 
115
137
  act_on_action :show, :update, format: :json
116
- act_on_action :show, format: :html
138
+ act_on_action :show, :update, format: :html
117
139
 
118
140
  rescue_act_from ActiveRecord::RecordNotFound, ActiveRecord::RecordNotSaved, format: :json, with: :handle_json_error
119
- rescue_act_from ActiveRecord::RecordNotSaved, action: :show, format: :html, with: -> { redirect_to "/events" }
141
+ rescue_act_from ActiveRecord::RecordNotFound, action: :show, format: :html, with: -> { redirect_to "/events" }
120
142
  rescue_act_from ActiveRecord::RecordNotSaved, action: :update, format: :html, with: -> { render :edit }
121
143
 
122
144
  def show
@@ -159,14 +181,14 @@ The above is equivalent to the following:
159
181
 
160
182
  def handle_not_found_error(error)
161
183
  respond_to do |format|
162
- format.html { redirect_to "/events" }
184
+ format.html { action_name == "show" ? redirect_to("/events") : raise(error) }
163
185
  format.json { handle_json_error(error) }
164
186
  end
165
187
  end
166
188
 
167
189
  def handle_not_saved_error(error)
168
190
  respond_to do |format|
169
- format.html { render :edit }
191
+ format.html { action_name == "update" ? render(:edit) : raise(error) }
170
192
  format.json { handle_json_error(error) }
171
193
  end
172
194
  end
@@ -176,13 +198,71 @@ The above is equivalent to the following:
176
198
  end
177
199
  ```
178
200
 
201
+ ## Lifecycle
202
+
203
+ `MimeActor::Action` handles the actions declared with `act_on_action`, other actions run as usual.
204
+
205
+ Including `MimeActor::Action` adds `before_action :negotiate_act_format` where the `include` is. A request to a declared action runs in this order:
206
+
207
+ 1. The `before_action` callbacks declared before the `include`, including those of the parent controllers.
208
+ 2. `negotiate_act_format`:
209
+ - checks the handlers of every declared format exist, raises `MimeActor::ActorNotFound` for a missing `with:` method, or `AbstractController::ActionNotFound` for a format without a `with:` handler when the action has no method;
210
+ - picks the format from the request among the declared formats, raises `ActionController::UnknownFormat` (`406 Not Acceptable`) when none is accepted;
211
+ - sets `act_action` and `act_format`.
212
+ 3. The `before_action` callbacks declared after the `include`, including those of the subclasses.
213
+ 4. The act: `act_before`, `act_around`, the action method or the `with:` handler of the format, then `act_after`.
214
+ 5. The default render, when nothing has responded.
215
+ 6. The `after_action` callbacks.
216
+
217
+ The gem imposes the following:
218
+
219
+ - An `act_before` halts the act when it responds (`render`, `redirect_to`, `head`), like `before_action`, or when it throws `:abort`. The remaining act callbacks and the action are skipped. A halt without a response still gets the default render (step 5), which renders the template of the action if there is one.
220
+ - `rescue_act_from` rescues the errors raised by the act (step 4). The errors it does not rescue, and those raised outside the act, go to `rescue_from`, where `act_format` can be read.
221
+ - `act_action` and `act_format` are private readers, set from the negotiation until the end of the request, `nil` before it or for an action not declared.
222
+ - An act handler (a `with:` method, Proc or block) is called without arguments, it reads `act_action`/`act_format` instead. A rescue handler is called with the error unless it takes no arguments, like `rescue_from`.
223
+ - `request.format` is left as Rails sets it, `act_format` is the negotiated format. To expose it as `request.format`, set it in a `before_action` declared after the `include`, it also changes `params[:format]`:
224
+ ```rb
225
+ before_action { request.format = act_format if act_format }
226
+ ```
227
+ - The format is negotiated once, from the request at step 2. A `before_action` that changes `request.format` must run before it: declare it before the `include`, or declare `negotiate_act_format` again after it. Otherwise the act responds to the negotiated format only, and the request fails with `406`.
228
+ - `negotiate_act_format` moves like any `before_action`: declare it again to run it after the callbacks declared so far, or `skip_before_action :negotiate_act_format` to negotiate when the action runs (step 4).
229
+
230
+ #### Authentication
231
+
232
+ The position of the `include` decides whether a request is negotiated or authenticated first.
233
+
234
+ Negotiate first, with the `include` before the authentication: a request for a format the action does not declare is rejected with `406` before it is authenticated, so the formats of an action are visible to a signed out client.
235
+
236
+ Authenticate first, by declaring the negotiation again after the authentication: a signed out request is rejected or redirected whatever its format, and the authentication runs for requests rejected with `406` afterwards.
237
+ ```rb
238
+ class ApplicationController < ActionController::Base
239
+ include MimeActor::Action
240
+
241
+ before_action :authenticate_user!
242
+ before_action :negotiate_act_format # declared again, runs after the authentication
243
+ end
244
+ ```
245
+
246
+ #### ActionController::Metal
247
+
248
+ A controller built on `ActionController::Metal` dispatches every public method below its first abstract ancestor as an action, including those of the modules `MimeActor::Action` brings in (`render`, `respond_to`, `run_callbacks`, ...). Include `MimeActor::Action` in an abstract controller, and declare the actions in its subclasses, the methods of an abstract controller are not actions:
249
+ ```rb
250
+ class MetalController < ActionController::Metal
251
+ abstract!
252
+ include MimeActor::Action
253
+ end
254
+
255
+ class EventsController < MetalController
256
+ act_on_action :show, format: :json, with: -> { self.response_body = "{}" }
257
+ end
258
+ ```
259
+
179
260
  ## Features
180
261
 
181
262
  - Action customisation for [ActionController][doc_action_controller] per MIME type
182
263
  - Customisation are deduplicated automatically when configured multiple times
183
264
  - Flexible rescue handler definition for the combination of Action/MIME type or both
184
- - Built on top of [ActionController::Metal::MimeResponds][doc_action_controller_mime_responds]
185
- - Fully compatible with other [ActionController][doc_action_controller] functionalities
265
+ - Built on top of [ActionController::MimeResponds][doc_action_controller_mime_responds]
186
266
 
187
267
  ## Documentation
188
268
 
@@ -210,7 +290,7 @@ gem install mime_actor
210
290
 
211
291
  After checking out the repo, run `bin/setup` to install dependencies. Then, run `bundle exec rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
212
292
 
213
- 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).
293
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, run the Release workflow on `main` with the version, it bumps the version, runs the tests, pushes the `.gem` file to [rubygems.org](https://rubygems.org), then commits the release with its tag.
214
294
 
215
295
  ## License
216
296
  Please see [LICENSE](https://github.com/ryancyq/mime_actor/blob/main/LICENSE) for licensing details.
@@ -225,8 +305,6 @@ Bug reports and pull requests are welcome on GitHub at [https://github.com/ryanc
225
305
  [ci_workflows]: https://github.com/ryancyq/mime_actor/actions/workflows/ci.yml
226
306
  [coverage_badge]: https://codecov.io/gh/ryancyq/mime_actor/graph/badge.svg?token=4C091RHXC3
227
307
  [coverage]: https://codecov.io/gh/ryancyq/mime_actor
228
- [maintainability_badge]: https://api.codeclimate.com/v1/badges/06689606dc3f3945dc1b/maintainability
229
- [maintainability]: https://codeclimate.com/github/ryancyq/mime_actor/maintainability
230
308
 
231
309
  [doc_mime_actor]: https://rubydoc.info/gems/mime_actor
232
310
  [doc_action_controller]: https://rubydoc.info/gems/actionpack/ActionController/Metal
@@ -2,78 +2,111 @@
2
2
 
3
3
  # :markup: markdown
4
4
 
5
- require "mime_actor/logging"
5
+ require "mime_actor/callbacks"
6
+ require "mime_actor/errors"
7
+ require "mime_actor/rescue"
6
8
  require "mime_actor/scene"
7
- require "mime_actor/stage"
8
9
 
9
10
  require "active_support/concern"
10
11
  require "active_support/lazy_load_hooks"
12
+ require "active_support/notifications"
13
+ require "abstract_controller/callbacks"
11
14
  require "abstract_controller/rendering"
15
+ require "action_controller/metal/exceptions"
12
16
  require "action_controller/metal/mime_responds"
13
17
 
14
18
  module MimeActor
15
19
  # # MimeActor Action
16
20
  #
17
- # `Action` is the recommended `Module` to be included in the `ActionController`.
21
+ # `Action` is the `Module` to be included in the `ActionController`.
18
22
  #
19
23
  # Provides intuitive way of `action` processing for a specific MIME type with callback + rescue handlers.
20
24
  #
25
+ # The act format is negotiated by `before_action :negotiate_act_format`, added where `Action` is included.
26
+ #
27
+ # Each act is instrumented as `act.mime_actor` with the `controller`, `action` and `format` in the payload.
28
+ #
21
29
  module Action
22
30
  extend ActiveSupport::Concern
23
31
 
32
+ include AbstractController::Callbacks # required by before_action
24
33
  include AbstractController::Rendering # required by MimeResponds
25
34
  include ActionController::MimeResponds
26
35
 
27
36
  include Scene
28
- include Stage
29
- include Logging
30
-
31
- # The core logic where rendering logics are collected as `Proc` and passed over to `ActionController::MimeResponds`
32
- #
33
- # @param block the block to be evaluated
34
- #
35
- # @example process `create` action
36
- # # it uses AbstractController#action_name to process
37
- # start_scene { create_internal }
38
- #
39
- # # it is equivalent to the following if `create` action is configured with `html` and `json` formats
40
- # def create
41
- # respond_to |format|
42
- # format.html { create_internal }
43
- # format.json { create_internal }
44
- # end
45
- # end
46
- #
47
- def start_scene(&block)
48
- action = action_name.to_sym
49
- formats = acting_scenes.fetch(action, {})
37
+ include Callbacks
38
+ include Rescue
50
39
 
51
- if formats.empty?
52
- logger.warn { "no format found for action: #{action_name.inspect}" }
53
- yield if block_given?
54
- else
55
- respond_to_scene(action, formats, block)
56
- end
40
+ Act = Struct.new(:action, :format)
41
+
42
+ included do
43
+ before_action :negotiate_act_format
44
+ end
45
+
46
+ def view_assigns
47
+ super.tap { |assigns| assigns.delete("mime_actor_act") }
57
48
  end
58
49
 
59
50
  private
60
51
 
61
- def respond_to_scene(action, formats, block)
52
+ # The `action` of the act, `nil` until the act format is negotiated.
53
+ def act_action
54
+ @mime_actor_act&.action
55
+ end
56
+
57
+ # The `format` of the act, `nil` until the act format is negotiated.
58
+ def act_format
59
+ @mime_actor_act&.format
60
+ end
61
+
62
+ # the act belongs to a single request
63
+ def process_action(*)
64
+ @mime_actor_act = nil
65
+ super
66
+ end
67
+
68
+ # Picks the `format` of a declared `action` from the request, raises `ActionController::UnknownFormat` if none.
69
+ def negotiate_act_format
70
+ return if @mime_actor_act
71
+
72
+ action = action_name.to_sym
73
+ return unless (scenes = self.class.acting_scenes[action])
74
+
75
+ verify_scene!(action)
76
+ mime = request.negotiate_mime(scenes.keys.map { |format| Mime[format] })
77
+ raise ActionController::UnknownFormat unless mime
78
+
79
+ @mime_actor_act = Act.new(action, mime.to_sym)
80
+ end
81
+
82
+ def method_for_action(action_name)
83
+ # an action hidden by a subclass must stay hidden
84
+ return super unless action_method?(action_name) && self.class.acting_scenes.key?(action_name.to_sym)
85
+
86
+ "play_scene"
87
+ end
88
+
89
+ def play_scene(*args)
90
+ negotiate_act_format # when the before_action is skipped
91
+ actor = self.class.acting_scenes.fetch(act_action).fetch(act_format)
62
92
  respond_to do |collector|
63
- formats.each do |format, actor|
64
- callable = actor.presence || block
65
- if callable.nil?
66
- logger.warn { "no #respond_to handler found for action: #{action.inspect} format: #{format.inspect}" }
67
- next
68
- end
69
-
70
- collector.public_send(format) do
71
- fill_run_sheet(action, format) { cue_actor(callable, action, format, action: action, format: format) }
72
- end
73
- end
93
+ collector.public_send(act_format) { play_act(actor, *args) }
94
+ end
95
+ end
96
+
97
+ def play_act(actor, *args)
98
+ payload = { controller: self.class.name, action: act_action, format: act_format }
99
+ ActiveSupport::Notifications.instrument("act.mime_actor", payload) do
100
+ run_callbacks(:act) { actor ? call_actor(actor) : send(act_action, *args) }
101
+ rescue StandardError => e
102
+ rescue_act(e) || raise
74
103
  end
75
104
  end
76
105
 
106
+ def call_actor(actor)
107
+ actor.is_a?(Proc) ? instance_exec(&actor) : send(actor)
108
+ end
109
+
77
110
  ActiveSupport.run_load_hooks(:mime_actor, self)
78
111
  end
79
112
  end
@@ -6,8 +6,6 @@ require "mime_actor/validator"
6
6
 
7
7
  require "active_support/callbacks"
8
8
  require "active_support/concern"
9
- require "active_support/core_ext/module/attr_internal"
10
- require "active_support/version"
11
9
 
12
10
  module MimeActor
13
11
  # # MimeActor Callbacks
@@ -24,21 +22,87 @@ module MimeActor
24
22
  # - prepend_act_around
25
23
  # - prepend_act_after
26
24
  #
25
+ # An `act_before` halts the act once it responds (render, redirect or head) or throws `:abort`,
26
+ # the remaining callbacks and the act are skipped.
27
+ #
27
28
  # NOTE: Calling the same callback multiple times will overwrite previous callback definitions.
28
29
  #
30
+ # Callbacks invocation sequence depends on the order of callback definition.
31
+ #
32
+ # @example callbacks with/without action filter
33
+ # act_before :my_act_before_one
34
+ # act_before :my_act_before_two, action: :create
35
+ # act_before :my_act_before_three
36
+ #
37
+ # act_around :my_act_around_one
38
+ # act_around :my_act_around_two, action: :create
39
+ # act_around :my_act_around_three
40
+ #
41
+ # act_after :my_act_after_one
42
+ # act_after :my_act_after_two, action: :create
43
+ # act_after :my_act_after_three
44
+ #
45
+ # # actual sequence:
46
+ # # - my_act_before_one
47
+ # # - my_act_before_two
48
+ # # - my_act_before_three
49
+ # # - my_act_around_one
50
+ # # - my_act_around_two
51
+ # # - my_act_around_three
52
+ # # - my_act_after_three
53
+ # # - my_act_after_two
54
+ # # - my_act_after_one
55
+ #
56
+ # @example callbacks with format filter
57
+ # act_before :my_act_before_one
58
+ # act_before :my_act_before_two, action: :create
59
+ # act_before :my_act_before_three, action: :create, format: :html
60
+ # act_before :my_act_before_four
61
+ #
62
+ # act_around :my_act_around_one
63
+ # act_around :my_act_around_two, action: :create, format: :html
64
+ # act_around :my_act_around_three, action: :create
65
+ # act_around :my_act_around_four
66
+ #
67
+ # act_after :my_act_after_one, format: :html
68
+ # act_after :my_act_after_two
69
+ # act_after :my_act_after_three, action: :create
70
+ # act_after :my_act_after_four
71
+ #
72
+ # # actual sequence:
73
+ # # - my_act_before_one
74
+ # # - my_act_before_two
75
+ # # - my_act_before_four
76
+ # # - my_act_before_three
77
+ # # - my_act_around_one
78
+ # # - my_act_around_two
79
+ # # - my_act_around_three
80
+ # # - my_act_around_four
81
+ # # - my_act_after_four
82
+ # # - my_act_after_three
83
+ # # - my_act_after_two
84
+ # # - my_act_after_one
85
+ #
29
86
  module Callbacks
30
87
  extend ActiveSupport::Concern
31
88
 
32
89
  include ActiveSupport::Callbacks
33
- include MimeActor::Validator
34
90
 
35
91
  LIFECYCLES = %i[before after around].freeze
36
92
 
37
- included do
38
- attr_internal_reader :act_action, :act_format
39
- define_callbacks :act, skip_after_callbacks_if_terminated: true
93
+ TERMINATOR = lambda do |controller, result_lambda|
94
+ halted = true
95
+ catch(:abort) do
96
+ result_lambda.call
97
+ halted = false
98
+ end
99
+ halted || controller.performed?
100
+ end
40
101
 
41
- ActiveSupport.version >= "7.2" ? generate_act_callback_methods : eval_act_callback_methods
102
+ included do
103
+ define_callbacks :act, terminator: TERMINATOR, skip_after_callbacks_if_terminated: true
104
+ # keep the callback runners out of `action_methods`
105
+ %i[_run_act_callbacks _run_act_callbacks! _act_callbacks].each { |name| private name if method_defined?(name) }
42
106
  end
43
107
 
44
108
  module ClassMethods
@@ -46,19 +110,14 @@ module MimeActor
46
110
  attr_reader :actions, :formats
47
111
 
48
112
  def initialize(actions, formats)
49
- if RUBY_VERSION < "2.6"
50
- @actions = actions ? Array(actions).to_set(&:to_sym) : nil
51
- @formats = formats ? Array(formats).to_set(&:to_sym) : nil
52
- else
53
- @actions = actions&.then { |a| Array(a).to_set(&:to_sym) }
54
- @formats = formats&.then { |f| Array(f).to_set(&:to_sym) }
55
- end
113
+ @actions = actions && Array(actions).to_set(&:to_sym)
114
+ @formats = formats && Array(formats).to_set(&:to_sym)
56
115
  end
57
116
 
58
117
  def match?(controller)
59
118
  matched = true
60
- matched &= actions.include?(controller.act_action) if !actions.nil? && controller.respond_to?(:act_action)
61
- matched &= formats.include?(controller.act_format) if !formats.nil? && controller.respond_to?(:act_format)
119
+ matched &= actions.include?(controller.send(:act_action)) unless actions.nil?
120
+ matched &= formats.include?(controller.send(:act_format)) unless formats.nil?
62
121
  matched
63
122
  end
64
123
 
@@ -67,6 +126,18 @@ module MimeActor
67
126
  alias around match?
68
127
  end
69
128
 
129
+ LIFECYCLES.each do |kind|
130
+ { append: false, prepend: true }.each do |type, prepend|
131
+ define_method(:"#{type}_act_#{kind}") do |*callbacks, action: nil, format: nil, &block|
132
+ validate_callback_options!(action, format)
133
+ configure_callbacks(callbacks, action, format, block) do |callback, options|
134
+ set_callback(:act, kind, callback, options.merge!(prepend: prepend))
135
+ end
136
+ end
137
+ end
138
+ alias_method :"act_#{kind}", :"append_act_#{kind}"
139
+ end
140
+
70
141
  private
71
142
 
72
143
  def configure_callbacks(callbacks, actions, formats, block)
@@ -80,116 +151,8 @@ module MimeActor
80
151
  end
81
152
 
82
153
  def validate_callback_options!(action, format)
83
- validate!(:action_or_actions, action) unless action.nil?
84
- validate!(:format_or_formats, format) unless format.nil?
85
- end
86
-
87
- def eval_act_callback_methods
88
- singleton_class.module_eval(<<-RUBY, __FILE__, __LINE__ + 1)
89
- # def append_act_before(*callbacks, action: nil, format: nil, &block)
90
- # validate_callback_options!(action, format)
91
- # configure_callbacks(callbacks, action, format, block) do |callback, options|
92
- # set_callback(:act, :before, callback, options.merge!(prepend: false))
93
- # end
94
- # end
95
- #
96
- # alias_method :act_before, :append_act_before
97
- #
98
- #{LIFECYCLES.map { |kind| act_callback_kind_template(kind, append: true) }.join(";")}
99
- #{LIFECYCLES.map { |kind| act_callback_kind_template(kind, append: false) }.join(";")}
100
- #{LIFECYCLES.map { |kind| "alias_method :act_#{kind}, :append_act_#{kind}" }.join(";")}
101
- RUBY
102
- end
103
-
104
- def generate_act_callback_methods
105
- require "active_support/code_generator"
106
- ActiveSupport::CodeGenerator.batch(singleton_class, __FILE__, __LINE__) do |owner|
107
- LIFECYCLES.each do |kind|
108
- owner.define_cached_method(:"append_act_#{kind}", as: :"act_#{kind}", namespace: :mime_callbacks) do |batch|
109
- batch << act_callback_kind_template(kind, append: true)
110
- end
111
- owner.define_cached_method(:"prepend_act_#{kind}", namespace: :mime_callbacks) do |batch|
112
- batch << act_callback_kind_template(kind, append: false)
113
- end
114
- end
115
- end
116
- end
117
-
118
- def act_callback_kind_template(kind, append:)
119
- type = append ? "append" : "prepend"
120
- <<-RUBY
121
- def #{type}_act_#{kind}(*callbacks, action: nil, format: nil, &block)
122
- validate_callback_options!(action, format)
123
- configure_callbacks(callbacks, action, format, block) do |callback, options|
124
- set_callback(:act, :#{kind}, callback, options.merge!(prepend: #{!append}))
125
- end
126
- end
127
- RUBY
128
- end
129
- end
130
-
131
- # Callbacks invocation sequence depends on the order of callback definition.
132
- #
133
- # @example callbacks with/without action filter
134
- # act_before :my_act_before_one
135
- # act_before :my_act_before_two, action: :create
136
- # act_before :my_act_before_three
137
- #
138
- # act_around :my_act_around_one
139
- # act_around :my_act_around_two, action: :create
140
- # act_around :my_act_around_three
141
- #
142
- # act_after :my_act_after_one
143
- # act_after :my_act_after_two, action: :create
144
- # act_after :my_act_after_three
145
- #
146
- # # actual sequence:
147
- # # - my_act_before_one
148
- # # - my_act_before_two
149
- # # - my_act_before_three
150
- # # - my_act_around_one
151
- # # - my_act_around_two
152
- # # - my_act_around_three
153
- # # - my_act_after_three
154
- # # - my_act_after_two
155
- # # - my_act_after_one
156
- #
157
- # @example callbacks with format filter
158
- # act_before :my_act_before_one
159
- # act_before :my_act_before_two, action: :create
160
- # act_before :my_act_before_three, action: :create, format: :html
161
- # act_before :my_act_before_four
162
- #
163
- # act_around :my_act_around_one
164
- # act_around :my_act_around_two, action: :create, format: :html
165
- # act_around :my_act_around_three, action: :create
166
- # act_around :my_act_around_four
167
- #
168
- # act_after :my_act_after_one, format: :html
169
- # act_after :my_act_after_two
170
- # act_after :my_act_after_three, action: :create
171
- # act_after :my_act_after_four
172
- #
173
- # # actual sequence:
174
- # # - my_act_before_one
175
- # # - my_act_before_two
176
- # # - my_act_before_four
177
- # # - my_act_before_three
178
- # # - my_act_around_one
179
- # # - my_act_around_two
180
- # # - my_act_around_three
181
- # # - my_act_around_four
182
- # # - my_act_after_four
183
- # # - my_act_after_three
184
- # # - my_act_after_two
185
- # # - my_act_after_one
186
- #
187
- def run_act_callbacks(action:, format:)
188
- @_act_action = action.to_sym
189
- @_act_format = format.to_sym
190
-
191
- run_callbacks :act do
192
- yield if block_given?
154
+ Validator.validate!(:action_or_actions, action) unless action.nil?
155
+ Validator.validate!(:format_or_formats, format) unless format.nil?
193
156
  end
194
157
  end
195
158
  end