Last active
          August 29, 2015 14:01 
        
      - 
      
- 
        Save skinofstars/0186d8514148364c7188 to your computer and use it in GitHub Desktop. 
    nested hashes and arays to a nice OpenStruct 
  
        
  
    
      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
    
  
  
    
  | require 'ostruct' | |
| # use dot notation on nested hash/arrays | |
| # based on http://andreapavoni.com/blog/2013/4/create-recursive-openstruct-from-a-ruby-hash/#.U3NjHXWx3AF | |
| # but extended to deal with arrays | |
| # or you could just use https://github.com/jsuchal/hashugar | |
| class DeepStruct < OpenStruct | |
| def initialize(hash=nil) | |
| @table = {} | |
| @hash_table = {} | |
| if hash | |
| hash.each do |k,v| | |
| if v.is_a?(Hash) | |
| @table[k.to_sym] = self.class.new(v) | |
| elsif v.is_a?(Array) | |
| arr = Array.new | |
| v.each {|j| arr.push self.class.new(j) } | |
| @table[k.to_sym] = arr | |
| else | |
| @table[k.to_sym] = v | |
| end | |
| @hash_table[k.to_sym] = v | |
| new_ostruct_member(k) | |
| end | |
| end | |
| end | |
| def to_h | |
| @hash_table | |
| end | |
| end | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment