Created
December 4, 2013 12:56
-
-
Save alexanderk23/7787043 to your computer and use it in GitHub Desktop.
DeepOpenStruct with recursive to_h
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
| class DeepOpenStruct < OpenStruct | |
| def to_h | |
| convert_to_hash_recursive self.dup | |
| end | |
| def self.load item | |
| raise ArgumentError, "DeepOpenStruct must be passed a Hash or Array" unless(item.is_a?(Hash) || item.is_a?(Array)) | |
| self.convert_from_hash_recursive item | |
| end | |
| private | |
| def self.convert_from_hash_recursive obj | |
| result = obj | |
| case result | |
| when Hash | |
| result = result.dup | |
| result.each do |k,v| | |
| result[k] = convert_from_hash_recursive(v) | |
| end | |
| result = DeepOpenStruct.new result | |
| when Array | |
| result = result.map { |v| convert_from_hash_recursive(v) } | |
| end | |
| result | |
| end | |
| def convert_to_hash_recursive obj | |
| result = obj | |
| case result | |
| when OpenStruct | |
| result = result.marshal_dump | |
| result.each do |k,v| | |
| result[k] = convert_to_hash_recursive(v) | |
| end | |
| when Array | |
| result = result.map { |v| convert_to_hash_recursive(v) } | |
| end | |
| result | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment