Skip to content

Commit

Permalink
Merge pull request #1255 from namusyaka/allow-param-definition-in-rou…
Browse files Browse the repository at this point in the history
…te_param

Allow param type definition in route_param
  • Loading branch information
dblock committed Jan 25, 2016
2 parents d8818f1 + 0017824 commit 5712b5b
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
* [#1238](https://github.com/ruby-grape/grape/pull/1238): Call `after` of middleware on error - [@namusyaka](https://github.com/namusyaka).
* [#1243](https://github.com/ruby-grape/grape/pull/1243): Add `header` support for middleware - [@namusyaka](https://github.com/namusyaka).
* [#1252](https://github.com/ruby-grape/grape/pull/1252): Allow default to be a subset or equal to allowed values without raising IncompatibleOptionValues - [@jeradphelps](https://github.com/jeradphelps).
* [#1255](https://github.com/ruby-grape/grape/pull/1255): Allow param type definition in route_param - [@namusyaka](https://github.com/namusyaka)
* Your contribution here.

#### Fixes
Expand Down
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1148,6 +1148,19 @@ namespace :statuses do
end
```

You can also define a route parameter type by passing to `route_param`'s options.

```ruby
namespace :arithmetic do
route_param :n, type: Integer do
desc 'Returns in power'
get 'power' do
params[:n] ** params[:n]
end
end
end
```

### Custom Validators

```ruby
Expand Down
8 changes: 7 additions & 1 deletion lib/grape/dsl/routing.rb
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,13 @@ def reset_routes!
# @option options [Regexp] You may supply a regular expression that the declared parameter must meet.
def route_param(param, options = {}, &block)
options = options.dup
options[:requirements] = { param.to_sym => options[:requirements] } if options[:requirements].is_a?(Regexp)
options[:requirements] = {
param.to_sym => options[:requirements]
} if options[:requirements].is_a?(Regexp)

Grape::Validations::ParamsScope.new(api: self) do
requires param, type: options[:type]
end if options.key?(:type)
namespace(":#{param}", options, &block)
end

Expand Down
12 changes: 12 additions & 0 deletions spec/grape/api_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,18 @@ def app
get '/users/23'
expect(last_response.status).to eq(200)
end

context 'with param type definitions' do
it 'is used by passing to options' do
subject.namespace :route_param do
route_param :foo, type: Integer do
get { params.to_json }
end
end
get '/route_param/1234'
expect(last_response.body).to eq("{\"foo\":1234}")
end
end
end

describe '.route' do
Expand Down

0 comments on commit 5712b5b

Please sign in to comment.