lib/ruby/extensions/methoded_hash.rb in ruby-mext-0.16.0 vs lib/ruby/extensions/methoded_hash.rb in ruby-mext-0.16.1
- old
+ new
@@ -1,5 +1,14 @@
+#
+# +MethodedHash+
+#
+# is a subclass of Hash which basically will create an accessor method
+# for every key in the hash, transforming all sub-hashes into +MethodedHash+
+# classes and so on (recursive).
+#
+# Please note: it will *NOT* add a method if the method already exist.
+#
class MethodedHash < Hash
def initialize(h = {})
duplicate_hash(h)
self
@@ -29,12 +38,19 @@
def common_methodizer(k)
methodize(k)
end
+ #
+ # +methodize(key)+
+ #
+ # this is the method that normalizes keys (to be able to transform them in
+ # methods. Please note that "methodization" will only happen if the
+ # class does not already respond to a normalized key method.
+ #
def methodize(key)
nk = normalize_key(key)
- define_singleton_method(nk) { self[key] }
+ define_singleton_method(nk) { self[key] } unless self.respond_to?(nk)
end
def normalize_key(key)
ek = key.to_s.gsub(/\W/, '_')
ek.to_sym