Sha256: f5d38041d1d4d934bc0ea893ce6f75c4641094e636b9d0c73cfb8b0ba557ec0c

Contents?: true

Size: 1.23 KB

Versions: 1

Compression:

Stored size: 1.23 KB

Contents

class CleanHash
  class Indifferent
    def initialize data
      @data = data
    end

    # for debug
    def to_json
      JSON.pretty_generate @data
    end

    # for puts
    def to_ary
      [@data]
    end

    def key? name
      @data.key?(name.to_sym) || @data.key?(name.to_s)
    end

    def delete key
      @data.delete(key.to_sym) || @data.delete(key.to_s)
    end

    def to_h
      @data
    end

    def to_json *args
      @data.to_json *args
    end

    def [] key
      data = @data[key.to_sym]
      data = @data[key.to_s] if data.nil?

      if data.is_a?(Hash)
        self.class.new data
      else
        data
      end
    end

    def []= key, value
      key = key.to_sym unless key.class == Symbol
      @data.delete(key.to_s)
      @data[key] = value
    end

    def method_missing name, *args, &block
      return @data.send(name, *args, &block) if !@data[name] && @data.respond_to?(name)

      m = name.to_s

      if m.end_with?('=')
        m = m.sub('=', '')
        self[m] = args.first
      elsif m.end_with?('?')
        begin
          !self[m.sub('?', '')].nil?
        rescue NoMethodError
          false
        end
      elsif block
        self[m] = block
      else
        self[m]
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
clean-hash-0.5.6 ./lib/clean-hash/types/indifferent_type.rb