Sha256: 0527f5c48cb926fc7922dcdcfc508ed8d3553419f4b447ee2777a9ebb7aac384

Contents?: true

Size: 1008 Bytes

Versions: 9

Compression:

Stored size: 1008 Bytes

Contents

class Map
  class Struct
    instance_methods.each { |m| undef_method m unless m =~ /^__|object_id/ }

    attr :map

    def initialize(map)
      @map = map
    end

    def method_missing(method, *args, &block)
      method = method.to_s
      case method
        when /=$/
          key = method.chomp('=')
          value = args.shift
          @map[key] = value
        else
          key = method
          raise(IndexError, key) unless @map.has_key?(key)
          value = @map[key]
      end
      value.is_a?(Map) ? value.struct : value
    end

    Keys = lambda{|*keys| keys.flatten!; keys.compact!; keys.map!{|key| key.to_s}}

    delegates = %w(
      inspect
    )

    delegates.each do |delegate|
      module_eval <<-__, __FILE__, __LINE__
        def #{ delegate }(*args, &block)
          @map.#{ delegate }(*args, &block)
        end
      __
    end
  end

  def struct
    @struct ||= Struct.new(map=self)
  end

  def Map.struct(*args, &block)
    new(*args, &block).struct
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
map-2.3.0 lib/map/struct.rb
map-2.2.2 lib/map/struct.rb
map-2.2.1 lib/map/struct.rb
map-2.2.0 lib/map/struct.rb
map-2.1.0 lib/map/struct.rb
map-2.0.0 lib/map/struct.rb
map-1.7.0 lib/map/struct.rb
map-1.6.0 lib/map/struct.rb
map-1.5.1 lib/map/struct.rb