Hash.pass and Hash.block that also work with HashWithIndifferentAccess

A new version of the old pass/block hack, but this time they also work as expected on HashWithIndifferentAccess (params/session…)

When attr_protected or attr_accessible are just to complicated, a simple user.attributes = params[:user].pass(:name, :email) just works.
Or user.attributes = params[:user].block(:admin) for the opposite…

# lets through the keys in the argument
# >> {:one => 1, :two => 2, :three => 3}.pass(:one)
# => {:one=>1}
def pass(*selected_keys)
  tmp = self.dup
  dup.block(*selected_keys).keys.each{|k| tmp.delete k }
  tmp
end

# blocks the keys in the arguments
# >> {:one => 1, :two => 2, :three => 3}.block(:one)
# => {:two=>2, :three=>3}
def block(*blocked_keys)
  tmp = self.dup
  blocked_keys.each{|k| tmp.delete k }
  tmp
end

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s