Our daily Method #4: Hash#excluding en Hash#only

Geplaatst door Remco van 't Veer vr, 08 feb 2008 08:00:00 GMT

This will look familiar:


u = params[:user]
attr = if u[:password].blank?
  u.reject do |k,_| 
    [:password, :password_confirmation].include?(k)
  end
end
User.update_attributes(attr || u)

But it smells like something reusable. I would like to write:


u = params[:user]
attr = if u[:password].blank?
  u.excluding(:password, :password_confirmation)
end
User.update_attributes(attr || u)

Easily to implement, including its little brother only, with:


class Hash
  def excluding(*keys)
    reject{|k,_| keys.include?(k)}
  end

  def only(*keys)
    reject{|k,_| !keys.include?(k)}
  end
end

Disclaimer: the above example doesn’t really work in Rails because params is a hash with indifferent access. Making an indifferent variant is up you! :)

Geplaatst in , ,  | 2 reacties

Reacties

  1. James Deville zei 10 dagen later:

    In rails, only already exists, and you can use except instead of excluding.

  2. RemVee zei 10 dagen later:

    I can’t believe I missed Hash#except. But I can not find Rails’s Hash#only variant. I did find out Merb has a Hash#only method.

(Laat url/e-mail achter »)

   Voorvertoning