From 3ea29982fa1766d56933fc2ddcff7a113f1c9aa1 Mon Sep 17 00:00:00 2001 From: Eric Date: Wed, 19 Jun 2024 21:03:38 +0200 Subject: [PATCH 1/3] Add context in endpoint dsl like Grape::Middleware::Helpers --- lib/grape/dsl/inside_route.rb | 4 ++++ spec/grape/api_spec.rb | 19 +++++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/lib/grape/dsl/inside_route.rb b/lib/grape/dsl/inside_route.rb index 8a927550f1..548b813d34 100644 --- a/lib/grape/dsl/inside_route.rb +++ b/lib/grape/dsl/inside_route.rb @@ -461,6 +461,10 @@ def entity_representation_for(entity_class, object, options) def http_version env['HTTP_VERSION'] || env[Rack::SERVER_PROTOCOL] end + + def context + env[Grape::Env::API_ENDPOINT] + end end end end diff --git a/spec/grape/api_spec.rb b/spec/grape/api_spec.rb index df8bdbb432..338681363d 100644 --- a/spec/grape/api_spec.rb +++ b/spec/grape/api_spec.rb @@ -4404,4 +4404,23 @@ def uniqe_id_route expect(last_response.body).to eq('deprecated') end end + + context 'rescue_from context' do + subject { last_response } + + let(:api) do + Class.new(described_class) do + rescue_from :all do + error!(context.env, 400) + end + get { raise ArgumentError, 'Oops!' } + end + end + + let(:app) { api} + + before { get '/' } + + it { is_expected.to be_bad_request } + end end From 3d5d2676cee57a913826371892e853c24480f02c Mon Sep 17 00:00:00 2001 From: Eric Date: Wed, 19 Jun 2024 21:08:10 +0200 Subject: [PATCH 2/3] Add CHANGELOG Fix rubocop --- CHANGELOG.md | 1 + spec/grape/api_spec.rb | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4b27d60b40..095129d25c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ #### Fixes +* [#2453](https://github.com/ruby-grape/grape/pull/2453): Fix context in rescue_from - [@ericproulx](https://github.com/ericproulx). * Your contribution here. ### 2.1.0 (2024/06/15) diff --git a/spec/grape/api_spec.rb b/spec/grape/api_spec.rb index 338681363d..fbd0ee38c7 100644 --- a/spec/grape/api_spec.rb +++ b/spec/grape/api_spec.rb @@ -4417,7 +4417,7 @@ def uniqe_id_route end end - let(:app) { api} + let(:app) { api } before { get '/' } From e6aee220f7c3977c2f5386aacdc355a9c60b9d09 Mon Sep 17 00:00:00 2001 From: Eric Date: Wed, 19 Jun 2024 21:19:50 +0200 Subject: [PATCH 3/3] Change to self --- lib/grape/dsl/inside_route.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/grape/dsl/inside_route.rb b/lib/grape/dsl/inside_route.rb index 548b813d34..c73eb7c773 100644 --- a/lib/grape/dsl/inside_route.rb +++ b/lib/grape/dsl/inside_route.rb @@ -463,7 +463,7 @@ def http_version end def context - env[Grape::Env::API_ENDPOINT] + self end end end