Skip to content

Commit a401b52

Browse files
committed
Merge pull request #512 from dblock/request-globals
Don't create Grape::Request multiple times.
2 parents 390ce93 + 22b3aef commit a401b52

File tree

11 files changed

+35
-33
lines changed

11 files changed

+35
-33
lines changed

CHANGELOG.md

+2
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ Next Release
22
============
33

44
#### Features
5+
56
* [#510](https://github.com/intridea/grape/pull/510): Support lambda-based default values for params - [@myitcv](https://github.com/myitcv).
67
* [#511](https://github.com/intridea/grape/pull/511): Add `required` option for OAuth2 middleware - [@bcm](https://github.com/bcm).
78
* Your contribution here.
@@ -13,6 +14,7 @@ Next Release
1314
* [#495](https://github.com/intridea/grape/pull/495): Fix `ParamsScope#params` for parameters nested inside arrays - [@asross](https://github.com/asross).
1415
* [#498](https://github.com/intridea/grape/pull/498): Dry up options and headers logic, allow headers to be passed to OPTIONS requests - [@karlfreeman](https://github.com/karlfreeman).
1516
* [#500](https://github.com/intridea/grape/pull/500): Skip entity auto-detection when explicitely passed - [@yaneq](https://github.com/yaneq).
17+
* [#512](https://github.com/intridea/grape/pull/512): Don't create `Grape::Request` multiple times - [@dblock](https://github.com/dblock).
1618
* Your contribution here.
1719

1820

README.md

+2-3
Original file line numberDiff line numberDiff line change
@@ -360,14 +360,14 @@ Optional parameters can have a default value.
360360
params do
361361
optional :color, type: String, default: 'blue'
362362
optional :random_number, type: Integer, default: -> { Random.rand(1..100) }
363-
optional :non_random_number, type: Integer, default: Random.rand(1..100)
363+
optional :non_random_number, type: Integer, default: Random.rand(1..100)
364364
end
365365
```
366366

367367
Parameters can be restricted to a specific set of values with the `:values` option.
368368

369369
Default values are eagerly evaluated. Above `:non_random_number` will evaluate to the same
370-
number for each call to the endpoint of this `params` block. To have the default evaluate
370+
number for each call to the endpoint of this `params` block. To have the default evaluate
371371
at calltime use a lambda, like `:random_number` above.
372372

373373
```ruby
@@ -1236,7 +1236,6 @@ GET /foo # 'root - foo - blah'
12361236
GET /foo/bar # 'root - foo - bar - blah'
12371237
```
12381238

1239-
12401239
## Anchoring
12411240

12421241
Grape by default anchors all request paths, which means that the request URL

lib/grape/endpoint.rb

+5-13
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ module Grape
55
# from inside a `get`, `post`, etc.
66
class Endpoint
77
attr_accessor :block, :source, :options, :settings
8-
attr_reader :env, :request
8+
attr_reader :env, :request, :headers, :params
99

1010
class << self
1111
# @api private
@@ -156,12 +156,6 @@ def call!(env)
156156
end
157157
end
158158

159-
# The parameters passed into the request as
160-
# well as parsed from URL segments.
161-
def params
162-
@params ||= @request.params
163-
end
164-
165159
# A filtering method that will return a hash
166160
# consisting only of keys that have been declared by a
167161
# `params` statement.
@@ -260,11 +254,6 @@ def header(key = nil, val = nil)
260254
end
261255
end
262256

263-
# Retrieves all available request headers.
264-
def headers
265-
@headers ||= @request.headers
266-
end
267-
268257
# Set response content-type
269258
def content_type(val)
270259
header('Content-Type', val)
@@ -377,7 +366,10 @@ def endpoints
377366
def run(env)
378367
@env = env
379368
@header = {}
380-
@request = Grape::Request.new(@env)
369+
370+
@request = Grape::Request.new(env)
371+
@params = @request.params
372+
@headers = @request.headers
381373

382374
extend helpers
383375
cookies.read(@request)

lib/grape/http/request.rb

+2-2
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ module Grape
22
class Request < Rack::Request
33

44
def params
5-
@env['grape.request.params'] = begin
5+
@params ||= begin
66
params = Hashie::Mash.new(super)
77
if env['rack.routing_args']
88
args = env['rack.routing_args'].dup
@@ -15,7 +15,7 @@ def params
1515
end
1616

1717
def headers
18-
@env['grape.request.headers'] ||= @env.dup.inject({}) do |h, (k, v)|
18+
@headers ||= env.dup.inject({}) do |h, (k, v)|
1919
if k.to_s.start_with? 'HTTP_'
2020
k = k[5..-1].gsub('_', '-').downcase.gsub(/^.|[-_\s]./) { |x| x.upcase }
2121
h[k] = v

lib/grape/middleware/auth/oauth2.rb

+9-1
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,17 @@ def before
1616
verify_token(token_parameter || token_header)
1717
end
1818

19+
def request
20+
@request ||= Grape::Request.new(env)
21+
end
22+
23+
def params
24+
@params ||= request.params
25+
end
26+
1927
def token_parameter
2028
Array(options[:parameter]).each do |p|
21-
return request[p] if request[p]
29+
return params[p] if params[p]
2230
end
2331
nil
2432
end

lib/grape/middleware/base.rb

+4-5
Original file line numberDiff line numberDiff line change
@@ -27,14 +27,13 @@ def call!(env)
2727

2828
# @abstract
2929
# Called before the application is called in the middleware lifecycle.
30-
def before; end
30+
def before
31+
end
32+
3133
# @abstract
3234
# Called after the application is called in the middleware lifecycle.
3335
# @return [Response, nil] a Rack SPEC response or nil to call the application afterwards.
34-
def after; end
35-
36-
def request
37-
Grape::Request.new(env)
36+
def after
3837
end
3938

4039
def response

lib/grape/middleware/formatter.rb

+4
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,10 @@ def after
4242

4343
private
4444

45+
def request
46+
@request ||= Rack::Request.new(env)
47+
end
48+
4549
# store read input in env['api.request.input']
4650
def read_body_input
4751
if (request.post? || request.put? || request.patch? || request.delete?) &&

lib/grape/middleware/versioner/param.rb

+2-3
Original file line numberDiff line numberDiff line change
@@ -27,14 +27,13 @@ def default_options
2727

2828
def before
2929
paramkey = options[:parameter]
30-
potential_version = request.params[paramkey]
31-
30+
potential_version = Rack::Utils.parse_nested_query(env['QUERY_STRING'])[paramkey]
3231
unless potential_version.nil?
3332
if options[:versions] && !options[:versions].find { |v| v.to_s == potential_version }
3433
throw :error, status: 404, message: "404 API Version Not Found", headers: { 'X-Cascade' => 'pass' }
3534
end
3635
env['api.version'] = potential_version
37-
env['rack.request.query_hash'].delete(paramkey)
36+
env['rack.request.query_hash'].delete(paramkey) if env.key? 'rack.request.query_hash'
3837
end
3938
end
4039

spec/grape/middleware/base_spec.rb

-5
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,6 @@
1313
subject.app.should == blank_app
1414
end
1515

16-
it 'is able to access the request' do
17-
subject.call({})
18-
subject.request.should be_kind_of(Rack::Request)
19-
end
20-
2116
it 'calls through to the app' do
2217
subject.call({}).should == [200, {}, 'Hi there.']
2318
end

spec/grape/middleware/formatter_spec.rb

+4-1
Original file line numberDiff line numberDiff line change
@@ -72,9 +72,12 @@ def to_xml
7272

7373
context 'detection' do
7474

75-
it 'uses the extension if one is provided' do
75+
it 'uses the xml extension if one is provided' do
7676
subject.call('PATH_INFO' => '/info.xml')
7777
subject.env['api.format'].should == :xml
78+
end
79+
80+
it 'uses the json extension if one is provided' do
7881
subject.call('PATH_INFO' => '/info.json')
7982
subject.env['api.format'].should == :json
8083
end

spec/grape/middleware/versioner/param_spec.rb

+1
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212

1313
it 'cuts (only) the version out of the params', focus: true do
1414
env = Rack::MockRequest.env_for("/awesome", { params: { "apiver" => "v1", "other_param" => "5" } })
15+
env['rack.request.query_hash'] = Rack::Utils.parse_nested_query(env['QUERY_STRING'])
1516
subject.call(env)[1]['rack.request.query_hash']["apiver"].should be_nil
1617
subject.call(env)[1]['rack.request.query_hash']["other_param"].should == "5"
1718
end

0 commit comments

Comments
 (0)