Sha256: 6a35446bd3b2ffe15d8c7d05c8d068f0580dea012767314c5010b1cee101d31c

Contents?: true

Size: 1.28 KB

Versions: 2

Compression:

Stored size: 1.28 KB

Contents

module Awestruct

  module AStructMixin

    def self.extended(o)
      class << o
        alias_method :original_entries, :entries
        undef entries
      end
    end

    def cascade_for_nils!
      @cascade_for_nils = true 
      self
    end

    def key?(key)
      super( key ) || super( key.to_sym ) || super( key.to_s )
    end

    def [](key)
      r = super( key ) || super( key.to_sym ) || super( key.to_s  )
      transform_entry( r )
    end

    def method_missing(sym, *args, &blk)
      type = sym.to_s[-1,1]
      name = sym.to_s.gsub(/[=!?]$/, '').to_sym
      case type
      when '='
        self[name] = args.first
      when '!'
        __send__(name, *args, &blk)
      when '?'
        self[name]
      else
        if key?(name)
          self[name]
        elsif @cascade_for_nils
          self[name] = AStruct.new.cascade_for_nils! 
          self[name]
        else
          nil
        end
      end
    end


    def transform_entry(entry)
      r = case(entry)
        when AStructMixin
          entry
        when Hash
          #AStruct.new( entry )
          entry.extend( AStructMixin )
        when Array
          entry.map!{|i| transform_entry(i)}
        else
          entry
      end
      r
    end

    def inspect
      "AStruct{...}"
    end
  
  end

end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
awestructx-0.4.1 lib/awestruct/astruct_mixin.rb
awestructx-0.4.0 lib/awestruct/astruct_mixin.rb