Class: MsgExtractor::Headers

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/msg_extractor/headers.rb

Overview

Parsed RFC 5322 transport headers with case-insensitive lookup.

  • [] and all are case-insensitive (e.g. h == h).

  • [] returns the first value for a header name.

  • all returns every value for a header name.

  • to_h keeps the original case of each header name and is first-value-wins when the same name appears more than once.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(fields) ⇒ Headers

Returns a new instance of Headers.



26
27
28
29
30
31
# File 'lib/msg_extractor/headers.rb', line 26

def initialize(fields)
  @fields = fields
  # Build a downcased-name → values hash for O(1) lookup.
  @index = {}
  @fields.each { |name, value| (@index[name.downcase] ||= []) << value }
end

Class Method Details

.parse(text) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/msg_extractor/headers.rb', line 12

def self.parse(text)
  return new([]) if text.nil? || text.empty?
  fields = []
  text.each_line(chomp: true) do |line|
    break if line.empty? # end of the header block
    if line.start_with?(" ", "\t")
      fields.last[1] << " " << line.strip unless fields.empty?
    elsif (match = /\A([!-9;-~]+):[ \t]*(.*)\z/.match(line))
      fields << [match[1], +match[2]]
    end
  end
  new(fields)
end

Instance Method Details

#[](key) ⇒ Object



33
# File 'lib/msg_extractor/headers.rb', line 33

def [](key) = @index[key.downcase]&.first

#all(key) ⇒ Object



34
# File 'lib/msg_extractor/headers.rb', line 34

def all(key) = (@index[key.downcase] || []).dup

#each(&block) ⇒ Object



35
# File 'lib/msg_extractor/headers.rb', line 35

def each(&block) = @fields.each(&block)

#empty?Boolean

Returns:

  • (Boolean)


37
# File 'lib/msg_extractor/headers.rb', line 37

def empty? = @fields.empty?

#to_hObject



36
# File 'lib/msg_extractor/headers.rb', line 36

def to_h = @fields.each_with_object({}) { |(name, value), h| h[name] ||= value }