diff --git a/CHANGELOG.md b/CHANGELOG.md index 6b20a38c45..0528add0d4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/README.md b/README.md index eda5fbe8c0..58c4867d0b 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/lib/grape/dsl/routing.rb b/lib/grape/dsl/routing.rb index cdfe76128d..699649c4df 100644 --- a/lib/grape/dsl/routing.rb +++ b/lib/grape/dsl/routing.rb @@ -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 diff --git a/spec/grape/api_spec.rb b/spec/grape/api_spec.rb index fc1b14a1fa..f758dd0d9a 100644 --- a/spec/grape/api_spec.rb +++ b/spec/grape/api_spec.rb @@ -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