Skip to content

Add support for procs in default value #959

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion lib/grape-swagger/doc_methods/parse_params.rb
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,9 @@ def document_range_values(settings)
end

def document_default_value(settings)
@parsed_param[:default] = settings[:default] if settings.key?(:default)
return unless settings.key?(:default)

@parsed_param[:default] = settings[:default].is_a?(Proc) ? settings[:default].call : settings[:default]
end

def document_type_and_format(settings, data_type)
Expand Down
49 changes: 49 additions & 0 deletions spec/swagger_v2/params_default_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# frozen_string_literal: true

require 'spec_helper'

describe 'Default param' do
def app
Class.new(Grape::API) do
format :json

desc 'Get with default proc value'
params do
optional :timestamp, type: String, default: proc { Time.now.utc.iso8601 },
desc: 'A timestamp with default value from proc'
optional :static_value, type: String, default: 'static',
desc: 'A parameter with static default value'
end
get '/with_default_proc' do
{ timestamp: params[:timestamp], static_value: params[:static_value] }
end

add_swagger_documentation
end
end

describe 'swagger documentation' do
subject do
get '/swagger_doc'
JSON.parse(last_response.body)
end

it 'resolves the proc to a value for default parameter' do
parameters = subject['paths']['/with_default_proc']['get']['parameters']

timestamp_param = parameters.find { |p| p['name'] == 'timestamp' }
expect(timestamp_param).to be_present
expect(timestamp_param['default']).to be_present
# The default value should be a string in ISO8601 format
expect(timestamp_param['default']).to match(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z/)
end

it 'correctly documents static default values' do
parameters = subject['paths']['/with_default_proc']['get']['parameters']

static_param = parameters.find { |p| p['name'] == 'static_value' }
expect(static_param).to be_present
expect(static_param['default']).to eq('static')
end
end
end