Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Hash Tricks (See related posts)

From: http://blog.caboo.se/articles/2006/06/11/stupid-hash-tricks

class Hash

  # lets through the keys in the argument
  # >> {:one => 1, :two => 2, :three => 3}.pass(:one)
  # => {:one=>1}
  def pass(*keys)
    tmp = self.clone
    tmp.delete_if {|k,v| ! keys.include?(k) }
    tmp
  end

  # blocks the keys in the arguments
  # >> {:one => 1, :two => 2, :three => 3}.block(:one)
  # => {:two=>2, :three=>3}
  def block(*keys)
    tmp = self.clone
    tmp.delete_if {|k,v| keys.include?(k) }
    tmp
  end

end


In case you don’t already see the utility of this:
def some_action
    # some script kiddie also passed in :bee, which we don't want tampered with _here_.
    @model = Model.create(params.pass(:foo, :bar))
  end

or those cases where you don’t want to let everything through and don’t want to resort to attr_protected or attr_accessible

Comments on this post

jrm posts on Jun 13, 2006 at 14:30
Kick ass. Thanks for posting this here too!
bitherder posts on Jun 17, 2006 at 23:26
You could also use the
Hash#inject()
method to get the same effect:

<pre>

class Hash
  def pass(*keys)
    inject({}) {|obj, p| k,v = p; obj[k] = v if keys.include?(k); obj }
  end

  def block(*keys)
    inject({}) {|obj, p| k,v = p; obj[k] = v unless keys.include?(k); obj }
  end
end

x = {:a => 1, :b => 2, :c => 3}

</pre>

You need to create an account or log in to post comments to this site.


Click here to browse all 5147 code snippets

Related Posts