Skip to content

Commit

Permalink
Add custom route segments.
Browse files Browse the repository at this point in the history
  • Loading branch information
Michael Bleigh committed Nov 12, 2010
1 parent 1bf41db commit d996563
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/grape/api.rb
Expand Up @@ -75,7 +75,7 @@ def compile_path(path)

def route(method, path_info, &block)
route_set.add_route(build_endpoint(&block),
:path_info => compile_path(path_info),
:path_info => Rack::Mount::Strexp.compile(compile_path(path_info)),
:request_method => method
)
end
Expand Down
15 changes: 15 additions & 0 deletions lib/grape/endpoint.rb
Expand Up @@ -2,13 +2,26 @@
require 'grape'

module Grape
# An Endpoint is the proxy scope in which all routing
# blocks are executed. In other words, any methods
# on the instance level of this class may be called
# from inside a `get`, `post`, etc. block.
class Endpoint
def initialize(&block)
@block = block
end

attr_reader :env, :request

def params
@params ||= request.params.merge(env['rack.routing_args'] || {}).inject({}) do |h,(k,v)|
h[k.to_s] = v
h[k.to_sym] = v
h
end
end

# Set or retrieve the HTTP status code.
def status(status = nil)
if status
@status = status
Expand All @@ -23,6 +36,8 @@ def status(status = nil)
end
end

# Set an individual header or retrieve
# all headers that have been set.
def header(key = nil, val = nil)
if key
val ? @header[key.to_s] = val : @header.delete(key.to_s)
Expand Down
20 changes: 20 additions & 0 deletions spec/grape/endpoint_spec.rb
Expand Up @@ -29,4 +29,24 @@ def app; subject end
last_response.headers['X-Awesome'].should == 'true'
end
end

describe '#params' do
it 'should be available to the caller' do
subject.get('/hey') do
params[:howdy]
end

get '/hey?howdy=hey'
last_response.body.should == 'hey'
end

it 'should parse from path segments' do
subject.get('/hey/:id') do
params[:id]
end

get '/hey/12'
last_response.body.should == '12'
end
end
end

0 comments on commit d996563

Please sign in to comment.