title: Ruby: How to prefix Namespaces in hash
body: <p>I am in a situation where I need to find out the level of the hash and apply a namespace for all elements in that level. </p>
  
  <p>This is the scenario:</p>
  
  <ol>
  <li><p>I have an object which is populated with my data.</p></li>
  <li><p>Next I convert the object to hash.</p>
  
  <pre><code>#convert Object to Hash
  def my_hash
    Hash[instance_variables.map { |var| [var[1..-1].to_sym, instance_variable_get(var)] }]
  end
  </code></pre></li>
  <li><p>Finally I would like to loop thru the hash and apply a different Namespace to my nested hash.</p>
  
  <ul>
  <li><p>Unfortunately I wasn't able to find a good solution to do this with savon gem directly:</p>
  
  <pre><code>soap.body = request_object.my_hash
  </code></pre></li>
  <li><p>I will inspect each element and try to find the nested level in classify method recursively: (this requires some more magic)</p>
  
  <pre><code>def classify(o)
    case o
      when Hash
        #Need to refactor this to prefix :data NS for nested hash, overwriting the default :mes NS. 
        h = {}
        o.each {|k,v| h[k] = classify(v)}
        h                 
      else
        o.class
    end 
  end
  soap.body = classify(request_object.my_hash)
  </code></pre></li>
  </ul></li>
  </ol>
  
  <p>It should look like this, The source hash:</p>
  
  <pre><code>{:UserTicket=&gt;'123',:ImpersonationUsername=&gt;'dave',:TicketSettings=&gt;{:ResourceId=&gt;'abcd',:ClientIp=&gt;'0',:Username=&gt;'bobby'}}
  </code></pre>
  
  <p>Output (where mes and data are two Namespaces):</p>
  
  <pre><code>{'mes:UserTicket'=&gt;'123','mes:ImpersonationUsername'=&gt;'dave','mes:TicketSettings'=&gt;{'data:ResourceId'=&gt;'abcd','data:ClientIp'=&gt;'0','data:Username'=&gt;'bobby'}}
  </code></pre>