Skip to content

Instantly share code, notes, and snippets.

@makevoid
Last active December 14, 2015 19:59
Show Gist options
  • Select an option

  • Save makevoid/5140504 to your computer and use it in GitHub Desktop.

Select an option

Save makevoid/5140504 to your computer and use it in GitHub Desktop.
Mhash: defines accessors methods for each hash key
# Mhash
#
# defines accessors methods for each hash key
#
#
# why?
# to enhance syntactic sugar and to let the refactoring transition to a real object easier
#
# usage:
#
# extend Mhash
# h = { a: "b" }
# to_mhash h
# p h.a #=> "b"
# h.a = "c"
# p h.a
module Mhash
def to_mhash(object)
if object.is_a? Array # probably an array of hashes
object.map{ |obj| hash_to_mhash obj }
else
hash_to_mhash object
end
end
private
def hash_to_mhash(object)
object.keys.each do |key|
eval "
def object.#{key}
self[:#{key}]
end"
eval "
def object.#{key}=(value)
self[:#{key}] = value
end"
end
object
end
end
class Hash
def to_mhash!
Mhash.to_mhash self
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment