Class: Mail::FieldList

Inherits:
Array
  • Object
show all
Includes:
Enumerable
Defined in:
lib/mail/field_list.rb

Overview

Field List class provides an enhanced array that keeps a list of email fields in order. And allows you to insert new fields without having to worry about the order they will appear in.

Instance Method Summary collapse

Instance Method Details

#add_field(field) ⇒ Object Also known as: <<


29
30
31
32
33
34
35
# File 'lib/mail/field_list.rb', line 29

def add_field(field)
  if field.singular?
    replace_field field
  else
    insert_field field
  end
end

#delete_field(name) ⇒ Object


67
68
69
# File 'lib/mail/field_list.rb', line 67

def delete_field(name)
  delete_if { |f| f.responsible_for? name }
end

#get_field(field_name) ⇒ Object


19
20
21
22
23
24
25
26
27
# File 'lib/mail/field_list.rb', line 19

def get_field(field_name)
  fields = select_fields(field_name)

  case fields.size
  when 0; nil
  when 1; fields.first
  else fields
  end
end

#has_field?(field_name) ⇒ Boolean

Returns:

  • (Boolean)

11
12
13
# File 'lib/mail/field_list.rb', line 11

def has_field?(field_name)
  any? { |f| f.responsible_for? field_name }
end

#insert_field(field) ⇒ Object

Insert the field in sorted order.

Heavily based on bisect.insort from Python, which is:

Copyright (C) 2001-2013 Python Software Foundation.
Licensed under <http://docs.python.org/license.html>
From <http://hg.python.org/cpython/file/2.7/Lib/bisect.py>

53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/mail/field_list.rb', line 53

def insert_field(field)
  lo, hi = 0, size
  while lo < hi
    mid = (lo + hi).div(2)
    if field < self[mid]
      hi = mid
    else
      lo = mid + 1
    end
  end

  insert lo, field
end

#replace_field(field) ⇒ Object


38
39
40
41
42
43
44
45
# File 'lib/mail/field_list.rb', line 38

def replace_field(field)
  if first_offset = index { |f| f.responsible_for? field.name }
    delete_field field.name
    insert first_offset, field
  else
    insert_field field
  end
end

#select_fields(field_name) ⇒ Object


15
16
17
# File 'lib/mail/field_list.rb', line 15

def select_fields(field_name)
  select { |f| f.responsible_for? field_name }
end

#summaryObject


71
72
73
# File 'lib/mail/field_list.rb', line 71

def summary
  map { |f| "<#{f.name}: #{f.value}>" }.join(", ")
end