Class: Rack::Utils::HeaderHash

Inherits:
Hash
  • Object
show all
Defined in:
lib/rack/utils.rb

Overview

A case-insensitive Hash that preserves the original case of a header when set.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hash = {}) ⇒ HeaderHash

Returns a new instance of HeaderHash.



331
332
333
334
335
# File 'lib/rack/utils.rb', line 331

def initialize(hash={})
  super()
  @names = {}
  hash.each { |k, v| self[k] = v }
end

Class Method Details

.new(hash = {}) ⇒ Object



327
328
329
# File 'lib/rack/utils.rb', line 327

def self.new(hash={})
  HeaderHash === hash ? hash : super(hash)
end

Instance Method Details

#[](k) ⇒ Object



349
350
351
# File 'lib/rack/utils.rb', line 349

def [](k)
  super(k) || super(@names[k.downcase])
end

#[]=(k, v) ⇒ Object



353
354
355
356
357
358
# File 'lib/rack/utils.rb', line 353

def []=(k, v)
  canonical = k.downcase
  delete k if @names[canonical] && @names[canonical] != k # .delete is expensive, don't invoke it unless necessary
  @names[k] = @names[canonical] = k
  super k, v
end

#delete(k) ⇒ Object



360
361
362
363
364
365
# File 'lib/rack/utils.rb', line 360

def delete(k)
  canonical = k.downcase
  result = super @names.delete(canonical)
  @names.delete_if { |name,| name.downcase == canonical }
  result
end

#eachObject



337
338
339
340
341
# File 'lib/rack/utils.rb', line 337

def each
  super do |k, v|
    yield(k, v.respond_to?(:to_ary) ? v.to_ary.join("\n") : v)
  end
end

#include?(k) ⇒ Boolean Also known as: has_key?, member?, key?

Returns:

  • (Boolean)


367
368
369
# File 'lib/rack/utils.rb', line 367

def include?(k)
  @names.include?(k) || @names.include?(k.downcase)
end

#merge(other) ⇒ Object



380
381
382
383
# File 'lib/rack/utils.rb', line 380

def merge(other)
  hash = dup
  hash.merge! other
end

#merge!(other) ⇒ Object



375
376
377
378
# File 'lib/rack/utils.rb', line 375

def merge!(other)
  other.each { |k, v| self[k] = v }
  self
end

#replace(other) ⇒ Object



385
386
387
388
389
# File 'lib/rack/utils.rb', line 385

def replace(other)
  clear
  other.each { |k, v| self[k] = v }
  self
end

#to_hashObject



343
344
345
346
347
# File 'lib/rack/utils.rb', line 343

def to_hash
  Hash[*map do |k, v|
    [k, v.respond_to?(:to_ary) ? v.to_ary.join("\n") : v]
  end.flatten]
end