Simple question, and I'm a little surprised that this isn't handled better in Rails already.
I am trying to scrub out some superfluous attributes from params
in a number of Rails API controllers with the except!()
method, like so:
params.except!( :format, :api_key, :controller, :action, :updated_at, :created_at )
Because these attributes are the same across a number of API endpoints, I wanted to store them in a Constant
in the API's BaseController
, like so:
PARAMS_TO_SCRUB = [ :format, :api_key, :controller, :action, :updated_at, :created_at ]
params.except!( PARAMS_TO_SCRUB ) # => Doesn't work.
But the except!()
method only accepts a splat of keys so none of the attributes get filtered:
# File activesupport/lib/active_support/core_ext/hash/except.rb, line 11
def except!(*keys)
keys.each { |key| delete(key) }
self
end
The work around I've setup now is to create a method in the BaseController
that scrubs the params
with the keys instead, like so:
def scrub_params
params.except!( :format, :api_key, :controller, :action, :updated_at, :created_at )
end
Is there no way to store a list of symbols like this?
Add *
before array variable:
PARAMS_TO_SCRUB = [ :format, :api_key, :controller, :action, :updated_at, :created_at ]
params.except!( *PARAMS_TO_SCRUB )
So, the method will change to:
def scrub_params ex_arr
params.except! *ex_arr
end
Or some global or class variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With