Simple Rails Improvements
Maybe I’ve been missing some function-names or missed some extensions, or maybe I’m just trying to do things too complex, but during the time I’ve worked on a new project in Rails I’ve been missing some functions. What I do then is extend Ruby/Rails’s base classes (Hooray for Ruby) so I can do the magic I want anyway. Todays example of some of those extensions are 2 new methods of the Hash class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class Hash # This function returns a hash excluding the keys given. def exclude (*key) key.inject(self.clone) do |me, key| me.reject{ |k,v| k == key } end end # This functions does a has_key? on multiple keys def has_keys? (*keys) keys.each do |key| return false unless has_key? key end return true end end |
Comments
-
Hey Jan - so I'm trying to do something similar, in that I'm extending Hash in one of my Rails projects. Unfortunately, I don't know where to put the file so that it's picked up by the interpreter. How do I do this?
Thanks!