Sha256: e37b85cdea82486f037f3431250eb3f16ae882bbd06ed4823af0692b9c90720f

Contents?: true

Size: 1.8 KB

Versions: 1

Compression:

Stored size: 1.8 KB

Contents

# raise error if accessing hash with method and key not found
# stict_hash = { foo: :bar }.to_ch :strict
# stict_hash[:not_found] # nil
# stict_hash.foo         # :bar
# stict_hash.not_found   # ArgumentError

class CleanHash
  MUTEX ||= Mutex.new

  def initialize data
    @data = data
  end

  # for debug
  def to_json
    JSON.pretty_generate @data
  end

  # for puts
  def to_ary
    [@data]
  end

  # overload key ruby method because it is common hash key name
  # still accessible via to_h.key
  def key
    self[:key]
  end

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

  def delete key
    out = []
    out.push @data.delete(key)
    out.push @data.delete(key.to_s)
    out.push @data.delete(key.to_sym) if key.respond_to?(:to_sym)
    out.each { |el| return el unless el.nil? }
    nil
  end

  def to_h
    @data
  end

  def to_json *args
    @data.to_json *args
  end

  def [] key
    data = @data[key]
    data = @data[key.to_s]   if data.nil? && !key.is_a?(String)
    data = @data[key.to_sym] if data.nil? && key.respond_to?(:to_sym)

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

  def []= key, value
    delete key
    MUTEX.synchronize do
      @data[key] = value
    end
  end

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

    m = name.to_s

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

  private

  def _method_missing_key key
    self[key].tap do |value|
      raise ArgumentError.new('Key not found: %s' % key) if value.nil?
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

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