views:

414

answers:

6

I often find myself writing this:

params.delete(:controller)  
params.delete(:action)  
params.delete(:other_key)  
redirect_to my_path(params)

The trail of deletes doesn't feel right and neither does:

[:controller, :action, :other_key].each do |k|
  params.delete(k)
end

Is there anything simpler and cleaner?

+4  A: 

Fire up a monkey patch?

class Hash
  def delete_keys!(*keys)
    keys.flatten.each do |k|
      delete(key)
    end

    self
  end

  def delete_keys(*keys)
    _dup = dup
    keys.flatten.each do |k|
      _dup.delete(key)
    end

    _dup
  end
end
tadman
Monkey patches are a tool of last resort.
Bob Aman
Monkey patches *that replace existing functions* are a tool of last resort. Monkey patches that add new functions are Ruby 101.
David Seiler
+2  A: 

I don't know what you think is wrong with your proposed solution. I suppose you want a delete_all method on Hash or something? If so, tadman's answer provides the solution. But frankly, for a one-off, I think your solution is extremely easy to follow. If you're using this frequently, you might want to wrap it up in a helper method.

Pesto
+2  A: 

Another way to phrase dmathieu's answer might be

params.delete_if { |k,v| [:controller, :action, :other_key].include? v }
MikeSep
I think you mean `params.delete_if { |k, v| [:controller, :action, :other_key].include? k }`
Telemachus
A: 

I'd be completely happy with the code you originally posted in your question.

[:controller, :action, :other_key].each { |k| params.delete(k) }
Bob Aman
+7  A: 

I'm guessing you're unaware of the Hash#except method ActiveSupport adds to Hash.

It would allow your code to be simplified to:

redirect_to my_path(params.except(:controller, :action, :other_key))

Also, you wouldn't have to monkey patch, since the Rails team did it for you!

Ben
Ahhh, I knew I'd seen this before but I couldn't remember where! (Hence my "this doesn't feel right" remark.) Thanks!
Mark Westling
No problem! Also, you can mark this answer as the official correct answer by clicking the check next to the voting controls to the left of this answer.
Ben
Nifty! Got to remember this one.
Jim
One of those lesser documented methods. I went looking for something like this while proposing an answer but didn't see it.
tadman
+1  A: 

While using Hash#except handles your problem, be aware that it introduces potential security issues. A good rule of thumb for handling any data from visitors is to use a whitelist approach. In this case, using Hash#slice instead.

params.slice!(:desired_param_1, :desired_param_2)

redirect_to my_path(params)

Eric