Skip to content

Commit

Permalink
Clone default params with each use (#1438)
Browse files Browse the repository at this point in the history
  • Loading branch information
Joe Faber committed Jul 14, 2016
1 parent 5936ee6 commit 706713c
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

#### Fixes

* [#1438](/~https://github.com/ruby-grape/grape/pull/1439): Fix for default param modification bug - [@jlfaber](/~https://github.com/jlfaber).
* [#1430](/~https://github.com/ruby-grape/grape/pull/1430): Fix for `declared(params)` inside `route_param` - [@Arkanain](/~https://github.com/Arkanain).
* [#1405](/~https://github.com/ruby-grape/grape/pull/1405): Fix priority of `rescue_from` clauses applying - [@hedgesky](/~https://github.com/hedgesky).
* [#1365](/~https://github.com/ruby-grape/grape/pull/1365): Fix finding exception handler in error middleware - [@ktimothy](/~https://github.com/ktimothy).
Expand Down
18 changes: 17 additions & 1 deletion lib/grape/validations/validators/default.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,23 @@ def initialize(attrs, options, required, scope)
end

def validate_param!(attr_name, params)
params[attr_name] = @default.is_a?(Proc) ? @default.call : @default unless params.key?(attr_name)
return if params.key? attr_name
params[attr_name] = if @default.is_a? Proc then @default.call
else case @default.class
# there's no foolproof way to know what will throw TypeError
# when clone is called.
when NilClass, TrueClass, FalseClass, Fixnum, Float, Symbol
# we know these classes don't support clone so just use the object
@default
else
# for the rest, try calling clone but use the object itself if that fails
begin
@default.clone
rescue TypeError
@default
end
end
end
end

def validate!(params)
Expand Down
41 changes: 41 additions & 0 deletions spec/grape/api/parameters_modification_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
require 'spec_helper'

describe Grape::Endpoint do
subject { Class.new(Grape::API) }

def app
subject
end

before do
subject.namespace :test do
params do
optional :foo, default: '-abcdef'
end
get do
params[:foo].slice!(0)
params[:foo]
end
end
end

context 'when route modifies param value' do
it 'param default should not change' do
get '/test'
expect(last_response.status).to eq 200
expect(last_response.body).to eq 'abcdef'

get '/test'
expect(last_response.status).to eq 200
expect(last_response.body).to eq 'abcdef'

get '/test?foo=-123456'
expect(last_response.status).to eq 200
expect(last_response.body).to eq '123456'

get '/test'
expect(last_response.status).to eq 200
expect(last_response.body).to eq 'abcdef'
end
end
end

0 comments on commit 706713c

Please sign in to comment.