Class: Mbox::Mail::Headers

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Enumerable
Defined in:
lib/mbox/mail/headers.rb,
lib/mbox/mail/headers/status.rb,
lib/mbox/mail/headers/content_type.rb

Defined Under Namespace

Classes: ContentType, Name, Status

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(start = {}) ⇒ Headers

Returns a new instance of Headers.



80
81
82
83
84
# File 'lib/mbox/mail/headers.rb', line 80

def initialize (start = {})
	@data = {}

	merge! start
end

Class Method Details

.parse(input) ⇒ Object



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

def self.parse (input)
	new.parse(input)
end

Instance Method Details

#[](name) ⇒ Object



86
87
88
# File 'lib/mbox/mail/headers.rb', line 86

def [] (name)
	@data[Name.parse(name)]
end

#[]=(name, value) ⇒ Object



90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/mbox/mail/headers.rb', line 90

def []= (name, value)
	name = Name.parse(name)

	if name == :status
		value = Status.parse(value)
	elsif name == :content_type
		value  = ContentType.parse(value)
	end

	if (tmp = @data[name]) && !tmp.is_a?(Array)
		@data[name] = [tmp]
	end

	if @data[name].is_a?(Array)
		@data[name] << value
	else
		@data[name] = value
	end
end

#delete(name) ⇒ Object



110
111
112
# File 'lib/mbox/mail/headers.rb', line 110

def delete (name)
	@data.delete(Headers.name_to_symbol(name))
end

#merge(other) ⇒ Object



122
123
124
# File 'lib/mbox/mail/headers.rb', line 122

def merge (other)
	clone.merge!(other)
end

#merge!(other) ⇒ Object



114
115
116
117
118
119
120
# File 'lib/mbox/mail/headers.rb', line 114

def merge! (other)
	other.each {|name, value|
		self[name] = value
	}

	self
end

#parse(input) ⇒ Object



126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/mbox/mail/headers.rb', line 126

def parse (input)
	input = if input.respond_to? :to_io
		input.to_io
	elsif input.is_a? String
		StringIO.new(input)
	else
		raise ArgumentError, 'I do not know what to do.'
	end

	last = nil

	until input.eof? || (line = input.readline).chomp.empty?
		if !line.match(/^\s/)
			next unless matches = line.match(/^([\w\-]+):\s*(.+)$/)

			whole, name, value = matches.to_a

			self[name] = value.strip
			last       = name
		elsif last && self[last]
			if self[last].is_a?(String)
				self[last] << " #{line.strip}"
			elsif self[last].is_a?(Array) && self[last].last.is_a?(String)
				self[last].last << " #{line.strip}"
			end
		end
	end

	self
end

#to_sObject



157
158
159
160
161
162
163
164
165
166
167
# File 'lib/mbox/mail/headers.rb', line 157

def to_s
	result = ''

	each {|name, values|
		[values].flatten.each {|value|
			result << "#{name}: #{value}\n"
		}
	}

	result
end