mime_actor 1.0.0 → 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: fbf21714856f466dcd213606d554c45634a8601d4d83c1157cf48979ab680c3a
4
- data.tar.gz: 6a3f623b039d7cd3fdc41b7bce4e4f827779aedf9537a87f2cafc6667d985c23
3
+ metadata.gz: 7e356a269b89d4a885a52eb435237038188d4fc31187184127c732b1208c3b84
4
+ data.tar.gz: cd49e1dbfa60cf07458fabb1d4681014346d55e4ecb10103d0965ff5d17700a6
5
5
  SHA512:
6
- metadata.gz: 9250e3561b80891aabeae7808abd60370be195d7d3139520f83b5346208be3e420841caed5002e073ab9417d3c7f815205f4f086d2c575bbf876070b4f82fb4a
7
- data.tar.gz: a93d0cb88e4fab401fd5dd6e02674f5ef834c19c9755577c8410073ed4ce30c364f0368eeda3fdb7960d4f81810297977cb89c512cb86418e95a05a9452918a7
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
 
@@ -190,9 +270,9 @@ You can find the documentation on [RubyDoc][doc_mime_actor].
190
270
 
191
271
  ## Requirements
192
272
 
193
- - Ruby: MRI 3.1+
194
- - ActiveSupport: 7.0+
195
- - ActionPack: 7.0+
273
+ - Ruby: MRI 2.5+
274
+ - ActiveSupport: 6.1+
275
+ - ActionPack: 6.1+
196
276
 
197
277
  ## Installation
198
278
 
@@ -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,10 +305,8 @@ 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
233
311
  [doc_action_controller_mime_responds]: https://rubydoc.info/gems/actionpack/ActionController/MimeResponds
234
- [doc_comparison]: https://github.com/ryancyq/mime_actor/blob/main/COMPARE.md
312
+ [doc_comparison]: https://github.com/ryancyq/mime_actor/blob/main/COMPARE.md
@@ -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