My Daily Technical Notes [ Ruby, Rails, Gems, Server Ops]

class RStruct
  # Recursive OpenStruct  # #
  def self.new(object)
    if object.is_a?(Hash)
      object = object.clone
      object.each do |key, value|
        object[key] = new(value)
      end
      OpenStruct.new(object)
    else
      object
    endendend

Example:

> a = {l1: {l2: {name: 'shiva'}}}
 => {:l1=>{:l2=>{:name=>"shiva"
> aa = RStruct.new(a)
 => #<OpenStruct l1=#<OpenStruct l2=#<OpenStruct name="shiva">>> 
> aa.l1.l2.name
 => "shiva"

View original post

Advertisements