Skip to content

Commit

Permalink
Add the action instance to the request environment
Browse files Browse the repository at this point in the history
I created a [new topic] on the Hanami Discourse about improving the
AppSignal APM instrumentation.

To group requests, we would like to know what action it took place in.
This information is currently not available in the request environment.

For us, the easiest would be to access the action instance. That gives
us the class information and a way to access the `params_class` to fetch
all the parameters of the request: query params and the body payload.

This change adds the action instance on a new request environment key
`hanami.action_instance`.

[new topic]: https://discourse.hanamirb.org/t/questions-for-improving-the-appsignal-apm-integration-with-hanami-2/989/3

I had to update one test to not fail on the action instance being
returned, which is not important for that spec I think.

Closes #445
  • Loading branch information
tombruijn committed Jun 27, 2024
1 parent 49e12e6 commit 6a329ea
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 1 deletion.
1 change: 1 addition & 0 deletions lib/hanami/action.rb
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,7 @@ def initialize(config: self.class.config)
# @since 0.1.0
# @api private
def call(env)
env[ACTION_INSTANCE] = self
request = nil
response = nil

Expand Down
4 changes: 4 additions & 0 deletions lib/hanami/action/constants.rb
Original file line number Diff line number Diff line change
Expand Up @@ -245,5 +245,9 @@ class Action
# @since 2.0.0
# @api private
DEFAULT_CHARSET = "utf-8"

# @since 2.2.0
# @api private
ACTION_INSTANCE = "hanami.action_instance"
end
end
4 changes: 3 additions & 1 deletion spec/support/fixtures.rb
Original file line number Diff line number Diff line change
Expand Up @@ -585,7 +585,9 @@ def handle(_req, _res)

class ParamsAction < Hanami::Action
def handle(req, res)
res.body = req.params.to_h.inspect
params = req.params.to_h
params.delete(Hanami::Action::ACTION_INSTANCE.to_sym)
res.body = params.inspect
end
end

Expand Down
8 changes: 8 additions & 0 deletions spec/unit/hanami/action_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,14 @@
expect(response.body).to eq(["Hi from TestAction!"])
end

it "sets the action instance on the request environment object" do
action = CallAction.new
env = {}
action.call(env)

expect(env[Hanami::Action::ACTION_INSTANCE]).to eq(action)
end

context "when an exception isn't handled" do
it "should raise an actual exception" do
expect { UncheckedErrorCallAction.new.call({}) }.to raise_error(RuntimeError)
Expand Down

0 comments on commit 6a329ea

Please sign in to comment.