Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an Array of Symbols to Rails' `except()!` Method

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:

In BaseController.rb

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?

like image 741
Joshua Pinter Avatar asked Dec 20 '22 15:12

Joshua Pinter


1 Answers

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.

like image 173
zishe Avatar answered Dec 30 '22 16:12

zishe