Last active
December 14, 2015 19:59
-
-
Save makevoid/5140504 to your computer and use it in GitHub Desktop.
Mhash: defines accessors methods for each hash key
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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