aboutsummaryrefslogtreecommitdiffstats
path: root/actionmailer
diff options
context:
space:
mode:
authorDavid Heinemeier Hansson <david@loudthinking.com>2004-11-24 01:04:44 +0000
committerDavid Heinemeier Hansson <david@loudthinking.com>2004-11-24 01:04:44 +0000
commitdb045dbbf60b53dbe013ef25554fd013baf88134 (patch)
tree257830e3c76458c8ff3d1329de83f32b23926028 /actionmailer
downloadrails-db045dbbf60b53dbe013ef25554fd013baf88134.tar.gz
rails-db045dbbf60b53dbe013ef25554fd013baf88134.tar.bz2
rails-db045dbbf60b53dbe013ef25554fd013baf88134.zip
Initial
git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@4 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
Diffstat (limited to 'actionmailer')
-rw-r--r--actionmailer/CHANGELOG19
-rw-r--r--actionmailer/MIT-LICENSE21
-rwxr-xr-xactionmailer/README102
-rwxr-xr-xactionmailer/Rakefile107
-rw-r--r--actionmailer/install.rb61
-rwxr-xr-xactionmailer/lib/action_mailer.rb43
-rw-r--r--actionmailer/lib/action_mailer/base.rb152
-rw-r--r--actionmailer/lib/action_mailer/mail_helper.rb17
-rwxr-xr-xactionmailer/lib/action_mailer/vendor/text/format.rb1447
-rwxr-xr-xactionmailer/lib/action_mailer/vendor/tmail.rb4
-rwxr-xr-xactionmailer/lib/action_mailer/vendor/tmail/address.rb223
-rwxr-xr-xactionmailer/lib/action_mailer/vendor/tmail/base64.rb52
-rwxr-xr-xactionmailer/lib/action_mailer/vendor/tmail/config.rb50
-rwxr-xr-xactionmailer/lib/action_mailer/vendor/tmail/encode.rb447
-rwxr-xr-xactionmailer/lib/action_mailer/vendor/tmail/facade.rb531
-rwxr-xr-xactionmailer/lib/action_mailer/vendor/tmail/header.rb893
-rwxr-xr-xactionmailer/lib/action_mailer/vendor/tmail/info.rb16
-rwxr-xr-xactionmailer/lib/action_mailer/vendor/tmail/loader.rb1
-rwxr-xr-xactionmailer/lib/action_mailer/vendor/tmail/mail.rb420
-rwxr-xr-xactionmailer/lib/action_mailer/vendor/tmail/mailbox.rb414
-rwxr-xr-xactionmailer/lib/action_mailer/vendor/tmail/mbox.rb1
-rwxr-xr-xactionmailer/lib/action_mailer/vendor/tmail/net.rb261
-rwxr-xr-xactionmailer/lib/action_mailer/vendor/tmail/obsolete.rb116
-rwxr-xr-xactionmailer/lib/action_mailer/vendor/tmail/parser.rb1503
-rwxr-xr-xactionmailer/lib/action_mailer/vendor/tmail/port.rb358
-rwxr-xr-xactionmailer/lib/action_mailer/vendor/tmail/scanner.rb22
-rwxr-xr-xactionmailer/lib/action_mailer/vendor/tmail/scanner_r.rb244
-rwxr-xr-xactionmailer/lib/action_mailer/vendor/tmail/stringio.rb260
-rwxr-xr-xactionmailer/lib/action_mailer/vendor/tmail/tmail.rb1
-rwxr-xr-xactionmailer/lib/action_mailer/vendor/tmail/utils.rb215
-rw-r--r--actionmailer/test/fixtures/templates/signed_up.rhtml3
-rw-r--r--actionmailer/test/fixtures/test_mailer/signed_up.rhtml3
-rwxr-xr-xactionmailer/test/mail_service_test.rb92
33 files changed, 8099 insertions, 0 deletions
diff --git a/actionmailer/CHANGELOG b/actionmailer/CHANGELOG
new file mode 100644
index 0000000000..f6c6961711
--- /dev/null
+++ b/actionmailer/CHANGELOG
@@ -0,0 +1,19 @@
+*0.4* (5)
+
+* Consolidated the server configuration options into Base#server_settings= and expanded that with controls for authentication and more [Marten]
+ NOTE: This is an API change that could potentially break your application if you used the old application form. Please do change!
+
+* Added Base#deliveries as an accessor for an array of emails sent out through that ActionMailer class when using the :test delivery option. [bitsweat]
+
+* Added Base#perform_deliveries= which can be set to false to turn off the actual delivery of the email through smtp or sendmail.
+ This is especially useful for functional testing that shouldn't send off real emails, but still trigger delivery_* methods.
+
+* Added option to specify delivery method with Base#delivery_method=. Default is :smtp and :sendmail is currently the only other option.
+ Sendmail is assumed to be present at "/usr/sbin/sendmail" if that option is used. [Kent Sibilev]
+
+* Dropped "include TMail" as it added to much baggage into the default namespace (like Version) [Chad Fowler]
+
+
+*0.3*
+
+* First release \ No newline at end of file
diff --git a/actionmailer/MIT-LICENSE b/actionmailer/MIT-LICENSE
new file mode 100644
index 0000000000..26f55e7799
--- /dev/null
+++ b/actionmailer/MIT-LICENSE
@@ -0,0 +1,21 @@
+Copyright (c) 2004 David Heinemeier Hansson
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
diff --git a/actionmailer/README b/actionmailer/README
new file mode 100755
index 0000000000..263da4f401
--- /dev/null
+++ b/actionmailer/README
@@ -0,0 +1,102 @@
+= Action Mailer -- Easy email delivery and testing
+
+Action Mailer is framework for designing email-service layers. These layers
+are used to consolidate code for sending out forgotten passwords, welcoming
+wishes on signup, invoices for billing, and any other use case that requires
+a written notification to either a person or another system.
+
+The framework works by setting up all the email details, except the body,
+in methods on the service layer. Subject, recipients, sender, and timestamp
+are all set up this way. An example of such a method:
+
+ def signed_up(recipient)
+ @recipients = recipient
+ @subject = "[Signed up] Welcome #{recipient}"
+ @from = "system@loudthinking.com"
+ @sent_on = Time.local(2004, 12, 12)
+
+ @body["recipient"] = recipient
+ end
+
+The body of the email is created by using an Action View template (regular
+ERb) that has the content of the @body hash available as instance variables.
+So the corresponding body template for the method above could look like this:
+
+ Hello there,
+
+ Mr. <%= @recipient %>
+
+And if the recipient was given as "david@loudthinking.com", the email
+generated would look like this:
+
+ Date: Sun, 12 Dec 2004 00:00:00 +0100
+ From: system@loudthinking.com
+ To: david@loudthinking.com
+ Subject: [Signed up] Welcome david@loudthinking.com
+
+ Hello there,
+
+ Mr. david@loudthinking.com
+
+You never actually call the instance methods like signed_up directly. Instead,
+you call class methods like deliver_* and create_* that are automatically
+created for each instance method. So if the signed_up method sat on
+ApplicationMailer, it would look like this:
+
+ ApplicationMailer.create_signed_up("david@loudthinking.com") # => tmail object for testing
+ ApplicationMailer.deliver_signed_up("david@loudthinking.com") # sends the email
+ ApplicationMailer.new.signed_up("david@loudthinking.com") # won't work!
+
+
+== Dependencies
+
+Action Mailer requires that the Action Pack is either available to be required immediately
+or is accessible as a GEM.
+
+
+== Bundled software
+
+* tmail 0.10.8 by Minero Aoki released under LGPL
+ Read more on http://i.loveruby.net/en/prog/tmail.html
+
+* Text::Format 0.63 by Austin Ziegler released under OpenSource
+ Read more on http://www.halostatue.ca/ruby/Text__Format.html
+
+
+== Download
+
+The latest version of Action Mailer can be found at
+
+* http://rubyforge.org/project/showfiles.php?group_id=361
+
+Documentation can be found at
+
+* http://actionmailer.rubyonrails.org
+
+
+== Installation
+
+You can install Action Mailer with the following command.
+
+ % [sudo] ruby install.rb
+
+from its distribution directory.
+
+
+== License
+
+Action Mailer is released under the MIT license.
+
+
+== Support
+
+The Action Mailer homepage is http://actionmailer.rubyonrails.org. You can find
+the Action Mailer RubyForge page at http://rubyforge.org/projects/actionmailer.
+And as Jim from Rake says:
+
+ Feel free to submit commits or feature requests. If you send a patch,
+ remember to update the corresponding unit tests. If fact, I prefer
+ new feature to be submitted in the form of new unit tests.
+
+For other information, feel free to ask on the ruby-talk mailing list (which
+is mirrored to comp.lang.ruby) or contact mailto:david@loudthinking.com. \ No newline at end of file
diff --git a/actionmailer/Rakefile b/actionmailer/Rakefile
new file mode 100755
index 0000000000..8ddc3179f2
--- /dev/null
+++ b/actionmailer/Rakefile
@@ -0,0 +1,107 @@
+require 'rubygems'
+require 'rake'
+require 'rake/testtask'
+require 'rake/rdoctask'
+require 'rake/packagetask'
+require 'rake/gempackagetask'
+require 'rake/contrib/rubyforgepublisher'
+
+PKG_BUILD = ENV['PKG_BUILD'] ? '.' + ENV['PKG_BUILD'] : ''
+PKG_NAME = 'actionmailer'
+PKG_VERSION = '0.4.0' + PKG_BUILD
+PKG_FILE_NAME = "#{PKG_NAME}-#{PKG_VERSION}"
+
+desc "Default Task"
+task :default => [ :test ]
+
+# Run the unit tests
+
+Rake::TestTask.new { |t|
+ t.libs << "test"
+ t.pattern = 'test/*_test.rb'
+ t.verbose = true
+}
+
+
+# Genereate the RDoc documentation
+
+Rake::RDocTask.new { |rdoc|
+ rdoc.rdoc_dir = 'doc'
+ rdoc.title = "Action Mailer -- Easy email delivery and testing"
+ rdoc.options << '--line-numbers --inline-source --main README'
+ rdoc.rdoc_files.include('README', 'CHANGELOG')
+ rdoc.rdoc_files.include('lib/action_mailer.rb')
+ rdoc.rdoc_files.include('lib/action_mailer/*.rb')
+}
+
+
+# Create compressed packages
+
+
+spec = Gem::Specification.new do |s|
+ s.platform = Gem::Platform::RUBY
+ s.name = PKG_NAME
+ s.summary = "Service layer for easy email delivery and testing."
+ s.description = %q{Makes it trivial to test and deliver emails sent from a single service layer.}
+ s.version = PKG_VERSION
+
+ s.author = "David Heinemeier Hansson"
+ s.email = "david@loudthinking.com"
+ s.rubyforge_project = "actionmailer"
+ s.homepage = "http://actionmailer.rubyonrails.org"
+
+ s.add_dependency('actionpack', '>= 0.9.5')
+
+ s.has_rdoc = true
+ s.requirements << 'none'
+ s.require_path = 'lib'
+ s.autorequire = 'action_mailer'
+
+ s.files = [ "rakefile", "install.rb", "README", "CHANGELOG", "MIT-LICENSE" ]
+ s.files = s.files + Dir.glob( "lib/**/*" ).delete_if { |item| item.include?( "CVS" ) }
+ s.files = s.files + Dir.glob( "test/**/*" ).delete_if { |item| item.include?( "CVS" ) }
+end
+
+Rake::GemPackageTask.new(spec) do |p|
+ p.gem_spec = spec
+ p.need_tar = true
+ p.need_zip = true
+end
+
+
+# Publish beta gem
+desc "Publish the API documentation"
+task :pgem => [:package] do
+ Rake::SshFilePublisher.new("davidhh@one.textdrive.com", "domains/rubyonrails.org/gems/gems", "pkg", "#{PKG_FILE_NAME}.gem").upload
+end
+
+# Publish documentation
+desc "Publish the API documentation"
+task :pdoc => [:rdoc] do
+ Rake::SshDirPublisher.new("davidhh@one.textdrive.com", "domains/rubyonrails.org/am", "doc").upload
+end
+
+desc "Publish to RubyForge"
+task :rubyforge do
+ Rake::RubyForgePublisher.new('actionmailer', 'webster132').upload
+end
+
+
+desc "Count lines in the main rake file"
+task :lines do
+ lines = 0
+ codelines = 0
+ Dir.foreach("lib/action_mailer") { |file_name|
+ next unless file_name =~ /.*rb/
+
+ f = File.open("lib/action_mailer/" + file_name)
+
+ while line = f.gets
+ lines += 1
+ next if line =~ /^\s*$/
+ next if line =~ /^\s*#/
+ codelines += 1
+ end
+ }
+ puts "Lines #{lines}, LOC #{codelines}"
+end
diff --git a/actionmailer/install.rb b/actionmailer/install.rb
new file mode 100644
index 0000000000..4791ab1f4c
--- /dev/null
+++ b/actionmailer/install.rb
@@ -0,0 +1,61 @@
+require 'rbconfig'
+require 'find'
+require 'ftools'
+
+include Config
+
+# this was adapted from rdoc's install.rb by ways of Log4r
+
+$sitedir = CONFIG["sitelibdir"]
+unless $sitedir
+ version = CONFIG["MAJOR"] + "." + CONFIG["MINOR"]
+ $libdir = File.join(CONFIG["libdir"], "ruby", version)
+ $sitedir = $:.find {|x| x =~ /site_ruby/ }
+ if !$sitedir
+ $sitedir = File.join($libdir, "site_ruby")
+ elsif $sitedir !~ Regexp.quote(version)
+ $sitedir = File.join($sitedir, version)
+ end
+end
+
+makedirs = %w{ action_mailer/vendor action_mailer/vendor/text action_mailer/vendor/tmail }
+makedirs.each {|f| File::makedirs(File.join($sitedir, *f.split(/\//)))}
+
+# deprecated files that should be removed
+# deprecated = %w{ }
+
+# files to install in library path
+files = %w-
+ action_mailer.rb
+ action_mailer/base.rb
+ action_mailer/mail_helper.rb
+ action_mailer/vendor/text/format.rb
+ action_mailer/vendor/tmail.rb
+ action_mailer/vendor/tmail/address.rb
+ action_mailer/vendor/tmail/base64.rb
+ action_mailer/vendor/tmail/config.rb
+ action_mailer/vendor/tmail/encode.rb
+ action_mailer/vendor/tmail/facade.rb
+ action_mailer/vendor/tmail/header.rb
+ action_mailer/vendor/tmail/info.rb
+ action_mailer/vendor/tmail/loader.rb
+ action_mailer/vendor/tmail/mail.rb
+ action_mailer/vendor/tmail/mailbox.rb
+ action_mailer/vendor/tmail/mbox.rb
+ action_mailer/vendor/tmail/net.rb
+ action_mailer/vendor/tmail/obsolete.rb
+ action_mailer/vendor/tmail/parser.rb
+ action_mailer/vendor/tmail/port.rb
+ action_mailer/vendor/tmail/scanner.rb
+ action_mailer/vendor/tmail/scanner_r.rb
+ action_mailer/vendor/tmail/stringio.rb
+ action_mailer/vendor/tmail/tmail.rb
+ action_mailer/vendor/tmail/utils.rb
+-
+
+# the acual gruntwork
+Dir.chdir("lib")
+# File::safe_unlink *deprecated.collect{|f| File.join($sitedir, f.split(/\//))}
+files.each {|f|
+ File::install(f, File.join($sitedir, *f.split(/\//)), 0644, true)
+}
diff --git a/actionmailer/lib/action_mailer.rb b/actionmailer/lib/action_mailer.rb
new file mode 100755
index 0000000000..48fe4ccb16
--- /dev/null
+++ b/actionmailer/lib/action_mailer.rb
@@ -0,0 +1,43 @@
+#--
+# Copyright (c) 2004 David Heinemeier Hansson
+#
+# Permission is hereby granted, free of charge, to any person obtaining
+# a copy of this software and associated documentation files (the
+# "Software"), to deal in the Software without restriction, including
+# without limitation the rights to use, copy, modify, merge, publish,
+# distribute, sublicense, and/or sell copies of the Software, and to
+# permit persons to whom the Software is furnished to do so, subject to
+# the following conditions:
+#
+# The above copyright notice and this permission notice shall be
+# included in all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+#++
+
+begin
+ require 'action_controller'
+rescue LoadError
+ # Action Pack is not already available, try RubyGems
+ require 'rubygems'
+ require_gem 'actionpack', '>= 0.9.0'
+end
+
+$:.unshift(File.dirname(__FILE__) + "/action_mailer/vendor/")
+
+require 'action_mailer/base'
+require 'action_mailer/mail_helper'
+require 'action_mailer/vendor/tmail'
+require 'net/smtp'
+
+ActionView::Base.class_eval { include MailHelper }
+
+old_verbose, $VERBOSE = $VERBOSE, nil
+TMail::Encoder.const_set("MAX_LINE_LEN", 200)
+$VERBOSE = old_verbose \ No newline at end of file
diff --git a/actionmailer/lib/action_mailer/base.rb b/actionmailer/lib/action_mailer/base.rb
new file mode 100644
index 0000000000..389499c8fa
--- /dev/null
+++ b/actionmailer/lib/action_mailer/base.rb
@@ -0,0 +1,152 @@
+module ActionMailer #:nodoc:
+ # Usage:
+ #
+ # class ApplicationMailer < ActionMailer::Base
+ # def post_notification(recipients, post)
+ # @recipients = recipients
+ # @subject = "[#{post.account.name} #{post.title}]"
+ # @body["post"] = post
+ # @from = post.author.email_address_with_name
+ # end
+ #
+ # def comment_notification(recipient, comment)
+ # @recipients = recipient.email_address_with_name
+ # @subject = "[#{comment.post.project.client.firm.account.name}]" +
+ # " Re: #{comment.post.title}"
+ # @body["comment"] = comment
+ # @from = comment.author.email_address_with_name
+ # @sent_on = comment.posted_on
+ # end
+ # end
+ #
+ # # After this post_notification will look for "templates/application_mailer/post_notification.rhtml"
+ # ApplicationMailer.template_root = "templates"
+ #
+ # ApplicationMailer.create_comment_notification(david, hello_world) # => a tmail object
+ # ApplicationMailer.deliver_comment_notification(david, hello_world) # sends the email
+ class Base
+ private_class_method :new
+
+ # Template root determines the base from which template references will be made.
+ cattr_accessor :template_root
+
+ # The logger is used for generating information on the mailing run if available.
+ # Can be set to nil for no logging. Compatible with both Ruby's own Logger and Log4r loggers.
+ cattr_accessor :logger
+
+ # Allows detailed configuration of the server:
+ # * <tt>:address</tt> Allows you to use a remote mail server. Just change it away from it's default "localhost" setting.
+ # * <tt>:port</tt> On the off change that your mail server doesn't run on port 25, you can change it.
+ # * <tt>:domain</tt> If you need to specify a HELO domain, you can do it here.
+ # * <tt>:user_name</tt> If your mail server requires authentication, set the username and password in these two settings.
+ # * <tt>:password</tt> If your mail server requires authentication, set the username and password in these two settings.
+ # * <tt>:authentication</tt> If your mail server requires authentication, you need to specify the authentication type here.
+ # This is a symbol and one of :plain, :login, :cram_md5
+ @@server_settings = {
+ :address => "localhost",
+ :port => 25,
+ :domain => 'localhost.localdomain',
+ :user_name => nil,
+ :password => nil,
+ :authentication => nil
+ }
+ cattr_accessor :server_settings
+
+
+ # Whether or not errors should be raised if the email fails to be delivered
+ @@raise_delivery_errors = true
+ cattr_accessor :raise_delivery_errors
+
+ # Defines a delivery method. Possible values are :smtp (default), :sendmail, and :test.
+ # Sendmail is assumed to be present at "/usr/sbin/sendmail".
+ @@delivery_method = :smtp
+ cattr_accessor :delivery_method
+
+ # Determines whether deliver_* methods are actually carried out. By default they are,
+ # but this can be turned off to help functional testing.
+ @@perform_deliveries = true
+ cattr_accessor :perform_deliveries
+
+ # Keeps an array of all the emails sent out through the Action Mailer with delivery_method :test. Most useful
+ # for unit and functional testing.
+ @@deliveries = []
+ cattr_accessor :deliveries
+
+ attr_accessor :recipients, :subject, :body, :from, :sent_on, :bcc, :cc
+
+ class << self
+ def method_missing(method_symbol, *parameters)#:nodoc:
+ case method_symbol.id2name
+ when /^create_([_a-z]*)/
+ create_from_action($1, *parameters)
+ when /^deliver_([_a-z]*)/
+ begin
+ deliver(send("create_" + $1, *parameters))
+ rescue Object => e
+ raise e if raise_delivery_errors
+ end
+ end
+ end
+
+ def mail(to, subject, body, from, timestamp = nil) #:nodoc:
+ deliver(create(to, subject, body, from, timestamp))
+ end
+
+ def create(to, subject, body, from, timestamp = nil) #:nodoc:
+ m = TMail::Mail.new
+ m.to, m.subject, m.body, m.from = to, subject, body, from
+ m.date = timestamp.respond_to?("to_time") ? timestamp.to_time : (timestamp || Time.now)
+ return m
+ end
+
+ def deliver(mail) #:nodoc:
+ logger.info "Sent mail:\n #{mail.encoded}" unless logger.nil?
+ send("perform_delivery_#{delivery_method}", mail) if perform_deliveries
+ end
+
+ private
+ def perform_delivery_smtp(mail)
+ Net::SMTP.start(server_settings[:address], server_settings[:port], server_settings[:domain],
+ server_settings[:user_name], server_settings[:password], server_settings[:authentication]) do |smtp|
+ smtp.sendmail(mail.encoded, mail.from_address, mail.destinations)
+ end
+ end
+
+ def perform_delivery_sendmail(mail)
+ IO.popen("/usr/sbin/sendmail -i -t","w+") do |sm|
+ sm.print(mail.encoded)
+ sm.flush
+ end
+ end
+
+ def perform_delivery_test(mail)
+ deliveries << mail
+ end
+
+ def create_from_action(method_name, *parameters)
+ mailer = new
+ mailer.body = {}
+ mailer.send(method_name, *parameters)
+
+ if String === mailer.body
+ mail = create(mailer.recipients, mailer.subject, mailer.body, mailer.from, mailer.sent_on)
+ else
+ mail = create(mailer.recipients, mailer.subject, render_body(mailer, method_name), mailer.from, mailer.sent_on)
+ end
+
+ mail.bcc = @bcc if @bcc
+ mail.cc = @cc if @cc
+
+ return mail
+ end
+
+ def render_body(mailer, method_name)
+ ActionView::Base.new(template_path, mailer.body).render_file(method_name)
+ end
+
+ def template_path
+ template_root + "/" + Inflector.underscore(self.to_s)
+ end
+ end
+ end
+end
diff --git a/actionmailer/lib/action_mailer/mail_helper.rb b/actionmailer/lib/action_mailer/mail_helper.rb
new file mode 100644
index 0000000000..0235fcdc61
--- /dev/null
+++ b/actionmailer/lib/action_mailer/mail_helper.rb
@@ -0,0 +1,17 @@
+require 'action_mailer/vendor/text/format'
+
+module MailHelper#:nodoc:
+ def block_format(text)
+ formatted = text.split(/\n\r\n/).collect { |paragraph|
+ Text::Format.new(
+ :columns => 72, :first_indent => 2, :body_indent => 2, :text => paragraph
+ ).format
+ }.join("\n")
+
+ # Make list points stand on their own line
+ formatted.gsub!(/[ ]*([*]+) ([^*]*)/) { |s| " #{$1} #{$2.strip}\n" }
+ formatted.gsub!(/[ ]*([#]+) ([^#]*)/) { |s| " #{$1} #{$2.strip}\n" }
+
+ formatted
+ end
+end \ No newline at end of file
diff --git a/actionmailer/lib/action_mailer/vendor/text/format.rb b/actionmailer/lib/action_mailer/vendor/text/format.rb
new file mode 100755
index 0000000000..591c69cf91
--- /dev/null
+++ b/actionmailer/lib/action_mailer/vendor/text/format.rb
@@ -0,0 +1,1447 @@
+#--
+# Text::Format for Ruby
+# Version 0.63
+#
+# Copyright (c) 2002 - 2003 Austin Ziegler
+#
+# $Id: format.rb,v 1.1.1.1 2004/10/14 11:59:57 webster132 Exp $
+#
+# ==========================================================================
+# Revision History ::
+# YYYY.MM.DD Change ID Developer
+# Description
+# --------------------------------------------------------------------------
+# 2002.10.18 Austin Ziegler
+# Fixed a minor problem with tabs not being counted. Changed
+# abbreviations from Hash to Array to better suit Ruby's
+# capabilities. Fixed problems with the way that Array arguments
+# are handled in calls to the major object types, excepting in
+# Text::Format#expand and Text::Format#unexpand (these will
+# probably need to be fixed).
+# 2002.10.30 Austin Ziegler
+# Fixed the ordering of the <=> for binary tests. Fixed
+# Text::Format#expand and Text::Format#unexpand to handle array
+# arguments better.
+# 2003.01.24 Austin Ziegler
+# Fixed a problem with Text::Format::RIGHT_FILL handling where a
+# single word is larger than #columns. Removed Comparable
+# capabilities (<=> doesn't make sense; == does). Added Symbol
+# equivalents for the Hash initialization. Hash initialization has
+# been modified so that values are set as follows (Symbols are
+# highest priority; strings are middle; defaults are lowest):
+# @columns = arg[:columns] || arg['columns'] || @columns
+# Added #hard_margins, #split_rules, #hyphenator, and #split_words.
+# 2003.02.07 Austin Ziegler
+# Fixed the installer for proper case-sensitive handling.
+# 2003.03.28 Austin Ziegler
+# Added the ability for a hyphenator to receive the formatter
+# object. Fixed a bug for strings matching /\A\s*\Z/ failing
+# entirely. Fixed a test case failing under 1.6.8.
+# 2003.04.04 Austin Ziegler
+# Handle the case of hyphenators returning nil for first/rest.
+# 2003.09.17 Austin Ziegler
+# Fixed a problem where #paragraphs(" ") was raising
+# NoMethodError.
+#
+# ==========================================================================
+#++
+
+module Text #:nodoc:
+ # = Introduction
+ #
+ # Text::Format provides the ability to nicely format fixed-width text with
+ # knowledge of the writeable space (number of columns), margins, and
+ # indentation settings.
+ #
+ # Copyright:: Copyright (c) 2002 - 2003 by Austin Ziegler
+ # Version:: 0.63
+ # Based On:: Perl
+ # Text::Format[http://search.cpan.org/author/GABOR/Text-Format0.52/lib/Text/Format.pm],
+ # Copyright (c) 1998 Gábor Egressy
+ # Licence:: Ruby's, Perl Artistic, or GPL version 2 (or later)
+ #
+ class Format
+ VERSION = '0.63'
+
+ # Local abbreviations. More can be added with Text::Format.abbreviations
+ ABBREV = [ 'Mr', 'Mrs', 'Ms', 'Jr', 'Sr' ]
+
+ # Formatting values
+ LEFT_ALIGN = 0
+ RIGHT_ALIGN = 1
+ RIGHT_FILL = 2
+ JUSTIFY = 3
+
+ # Word split modes (only applies when #hard_margins is true).
+ SPLIT_FIXED = 1
+ SPLIT_CONTINUATION = 2
+ SPLIT_HYPHENATION = 4
+ SPLIT_CONTINUATION_FIXED = SPLIT_CONTINUATION | SPLIT_FIXED
+ SPLIT_HYPHENATION_FIXED = SPLIT_HYPHENATION | SPLIT_FIXED
+ SPLIT_HYPHENATION_CONTINUATION = SPLIT_HYPHENATION | SPLIT_CONTINUATION
+ SPLIT_ALL = SPLIT_HYPHENATION | SPLIT_CONTINUATION | SPLIT_FIXED
+
+ # Words forcibly split by Text::Format will be stored as split words.
+ # This class represents a word forcibly split.
+ class SplitWord
+ # The word that was split.
+ attr_reader :word
+ # The first part of the word that was split.
+ attr_reader :first
+ # The remainder of the word that was split.
+ attr_reader :rest
+
+ def initialize(word, first, rest) #:nodoc:
+ @word = word
+ @first = first
+ @rest = rest
+ end
+ end
+
+ private
+ LEQ_RE = /[.?!]['"]?$/
+
+ def brk_re(i) #:nodoc:
+ %r/((?:\S+\s+){#{i}})(.+)/
+ end
+
+ def posint(p) #:nodoc:
+ p.to_i.abs
+ end
+
+ public
+ # Compares two Text::Format objects. All settings of the objects are
+ # compared *except* #hyphenator. Generated results (e.g., #split_words)
+ # are not compared, either.
+ def ==(o)
+ (@text == o.text) &&
+ (@columns == o.columns) &&
+ (@left_margin == o.left_margin) &&
+ (@right_margin == o.right_margin) &&
+ (@hard_margins == o.hard_margins) &&
+ (@split_rules == o.split_rules) &&
+ (@first_indent == o.first_indent) &&
+ (@body_indent == o.body_indent) &&
+ (@tag_text == o.tag_text) &&
+ (@tabstop == o.tabstop) &&
+ (@format_style == o.format_style) &&
+ (@extra_space == o.extra_space) &&
+ (@tag_paragraph == o.tag_paragraph) &&
+ (@nobreak == o.nobreak) &&
+ (@abbreviations == o.abbreviations) &&
+ (@nobreak_regex == o.nobreak_regex)
+ end
+
+ # The text to be manipulated. Note that value is optional, but if the
+ # formatting functions are called without values, this text is what will
+ # be formatted.
+ #
+ # *Default*:: <tt>[]</tt>
+ # <b>Used in</b>:: All methods
+ attr_accessor :text
+
+ # The total width of the format area. The margins, indentation, and text
+ # are formatted into this space.
+ #
+ # COLUMNS
+ # <-------------------------------------------------------------->
+ # <-----------><------><---------------------------><------------>
+ # left margin indent text is formatted into here right margin
+ #
+ # *Default*:: <tt>72</tt>
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>,
+ # <tt>#center</tt>
+ attr_reader :columns
+
+ # The total width of the format area. The margins, indentation, and text
+ # are formatted into this space. The value provided is silently
+ # converted to a positive integer.
+ #
+ # COLUMNS
+ # <-------------------------------------------------------------->
+ # <-----------><------><---------------------------><------------>
+ # left margin indent text is formatted into here right margin
+ #
+ # *Default*:: <tt>72</tt>
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>,
+ # <tt>#center</tt>
+ def columns=(c)
+ @columns = posint(c)
+ end
+
+ # The number of spaces used for the left margin.
+ #
+ # columns
+ # <-------------------------------------------------------------->
+ # <-----------><------><---------------------------><------------>
+ # LEFT MARGIN indent text is formatted into here right margin
+ #
+ # *Default*:: <tt>0</tt>
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>,
+ # <tt>#center</tt>
+ attr_reader :left_margin
+
+ # The number of spaces used for the left margin. The value provided is
+ # silently converted to a positive integer value.
+ #
+ # columns
+ # <-------------------------------------------------------------->
+ # <-----------><------><---------------------------><------------>
+ # LEFT MARGIN indent text is formatted into here right margin
+ #
+ # *Default*:: <tt>0</tt>
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>,
+ # <tt>#center</tt>
+ def left_margin=(left)
+ @left_margin = posint(left)
+ end
+
+ # The number of spaces used for the right margin.
+ #
+ # columns
+ # <-------------------------------------------------------------->
+ # <-----------><------><---------------------------><------------>
+ # left margin indent text is formatted into here RIGHT MARGIN
+ #
+ # *Default*:: <tt>0</tt>
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>,
+ # <tt>#center</tt>
+ attr_reader :right_margin
+
+ # The number of spaces used for the right margin. The value provided is
+ # silently converted to a positive integer value.
+ #
+ # columns
+ # <-------------------------------------------------------------->
+ # <-----------><------><---------------------------><------------>
+ # left margin indent text is formatted into here RIGHT MARGIN
+ #
+ # *Default*:: <tt>0</tt>
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>,
+ # <tt>#center</tt>
+ def right_margin=(r)
+ @right_margin = posint(r)
+ end
+
+ # The number of spaces to indent the first line of a paragraph.
+ #
+ # columns
+ # <-------------------------------------------------------------->
+ # <-----------><------><---------------------------><------------>
+ # left margin INDENT text is formatted into here right margin
+ #
+ # *Default*:: <tt>4</tt>
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
+ attr_reader :first_indent
+
+ # The number of spaces to indent the first line of a paragraph. The
+ # value provided is silently converted to a positive integer value.
+ #
+ # columns
+ # <-------------------------------------------------------------->
+ # <-----------><------><---------------------------><------------>
+ # left margin INDENT text is formatted into here right margin
+ #
+ # *Default*:: <tt>4</tt>
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
+ def first_indent=(f)
+ @first_indent = posint(f)
+ end
+
+ # The number of spaces to indent all lines after the first line of a
+ # paragraph.
+ #
+ # columns
+ # <-------------------------------------------------------------->
+ # <-----------><------><---------------------------><------------>
+ # left margin INDENT text is formatted into here right margin
+ #
+ # *Default*:: <tt>0</tt>
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
+ attr_reader :body_indent
+
+ # The number of spaces to indent all lines after the first line of
+ # a paragraph. The value provided is silently converted to a
+ # positive integer value.
+ #
+ # columns
+ # <-------------------------------------------------------------->
+ # <-----------><------><---------------------------><------------>
+ # left margin INDENT text is formatted into here right margin
+ #
+ # *Default*:: <tt>0</tt>
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
+ def body_indent=(b)
+ @body_indent = posint(b)
+ end
+
+ # Normally, words larger than the format area will be placed on a line
+ # by themselves. Setting this to +true+ will force words larger than the
+ # format area to be split into one or more "words" each at most the size
+ # of the format area. The first line and the original word will be
+ # placed into <tt>#split_words</tt>. Note that this will cause the
+ # output to look *similar* to a #format_style of JUSTIFY. (Lines will be
+ # filled as much as possible.)
+ #
+ # *Default*:: +false+
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
+ attr_accessor :hard_margins
+
+ # An array of words split during formatting if #hard_margins is set to
+ # +true+.
+ # #split_words << Text::Format::SplitWord.new(word, first, rest)
+ attr_reader :split_words
+
+ # The object responsible for hyphenating. It must respond to
+ # #hyphenate_to(word, size) or #hyphenate_to(word, size, formatter) and
+ # return an array of the word split into two parts; if there is a
+ # hyphenation mark to be applied, responsibility belongs to the
+ # hyphenator object. The size is the MAXIMUM size permitted, including
+ # any hyphenation marks. If the #hyphenate_to method has an arity of 3,
+ # the formatter will be provided to the method. This allows the
+ # hyphenator to make decisions about the hyphenation based on the
+ # formatting rules.
+ #
+ # *Default*:: +nil+
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
+ attr_reader :hyphenator
+
+ # The object responsible for hyphenating. It must respond to
+ # #hyphenate_to(word, size) and return an array of the word hyphenated
+ # into two parts. The size is the MAXIMUM size permitted, including any
+ # hyphenation marks.
+ #
+ # *Default*:: +nil+
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
+ def hyphenator=(h)
+ raise ArgumentError, "#{h.inspect} is not a valid hyphenator." unless h.respond_to?(:hyphenate_to)
+ arity = h.method(:hyphenate_to).arity
+ raise ArgumentError, "#{h.inspect} must have exactly two or three arguments." unless [2, 3].include?(arity)
+ @hyphenator = h
+ @hyphenator_arity = arity
+ end
+
+ # Specifies the split mode; used only when #hard_margins is set to
+ # +true+. Allowable values are:
+ # [+SPLIT_FIXED+] The word will be split at the number of
+ # characters needed, with no marking at all.
+ # repre
+ # senta
+ # ion
+ # [+SPLIT_CONTINUATION+] The word will be split at the number of
+ # characters needed, with a C-style continuation
+ # character. If a word is the only item on a
+ # line and it cannot be split into an
+ # appropriate size, SPLIT_FIXED will be used.
+ # repr\
+ # esen\
+ # tati\
+ # on
+ # [+SPLIT_HYPHENATION+] The word will be split according to the
+ # hyphenator specified in #hyphenator. If there
+ # is no #hyphenator specified, works like
+ # SPLIT_CONTINUATION. The example is using
+ # TeX::Hyphen. If a word is the only item on a
+ # line and it cannot be split into an
+ # appropriate size, SPLIT_CONTINUATION mode will
+ # be used.
+ # rep-
+ # re-
+ # sen-
+ # ta-
+ # tion
+ #
+ # *Default*:: <tt>Text::Format::SPLIT_FIXED</tt>
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
+ attr_reader :split_rules
+
+ # Specifies the split mode; used only when #hard_margins is set to
+ # +true+. Allowable values are:
+ # [+SPLIT_FIXED+] The word will be split at the number of
+ # characters needed, with no marking at all.
+ # repre
+ # senta
+ # ion
+ # [+SPLIT_CONTINUATION+] The word will be split at the number of
+ # characters needed, with a C-style continuation
+ # character.
+ # repr\
+ # esen\
+ # tati\
+ # on
+ # [+SPLIT_HYPHENATION+] The word will be split according to the
+ # hyphenator specified in #hyphenator. If there
+ # is no #hyphenator specified, works like
+ # SPLIT_CONTINUATION. The example is using
+ # TeX::Hyphen as the #hyphenator.
+ # rep-
+ # re-
+ # sen-
+ # ta-
+ # tion
+ #
+ # These values can be bitwise ORed together (e.g., <tt>SPLIT_FIXED |
+ # SPLIT_CONTINUATION</tt>) to provide fallback split methods. In the
+ # example given, an attempt will be made to split the word using the
+ # rules of SPLIT_CONTINUATION; if there is not enough room, the word
+ # will be split with the rules of SPLIT_FIXED. These combinations are
+ # also available as the following values:
+ # * +SPLIT_CONTINUATION_FIXED+
+ # * +SPLIT_HYPHENATION_FIXED+
+ # * +SPLIT_HYPHENATION_CONTINUATION+
+ # * +SPLIT_ALL+
+ #
+ # *Default*:: <tt>Text::Format::SPLIT_FIXED</tt>
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
+ def split_rules=(s)
+ raise ArgumentError, "Invalid value provided for split_rules." if ((s < SPLIT_FIXED) || (s > SPLIT_ALL))
+ @split_rules = s
+ end
+
+ # Indicates whether sentence terminators should be followed by a single
+ # space (+false+), or two spaces (+true+).
+ #
+ # *Default*:: +false+
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
+ attr_accessor :extra_space
+
+ # Defines the current abbreviations as an array. This is only used if
+ # extra_space is turned on.
+ #
+ # If one is abbreviating "President" as "Pres." (abbreviations =
+ # ["Pres"]), then the results of formatting will be as illustrated in
+ # the table below:
+ #
+ # extra_space | include? | !include?
+ # true | Pres. Lincoln | Pres. Lincoln
+ # false | Pres. Lincoln | Pres. Lincoln
+ #
+ # *Default*:: <tt>{}</tt>
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
+ attr_accessor :abbreviations
+
+ # Indicates whether the formatting of paragraphs should be done with
+ # tagged paragraphs. Useful only with <tt>#tag_text</tt>.
+ #
+ # *Default*:: +false+
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
+ attr_accessor :tag_paragraph
+
+ # The array of text to be placed before each paragraph when
+ # <tt>#tag_paragraph</tt> is +true+. When <tt>#format()</tt> is called,
+ # only the first element of the array is used. When <tt>#paragraphs</tt>
+ # is called, then each entry in the array will be used once, with
+ # corresponding paragraphs. If the tag elements are exhausted before the
+ # text is exhausted, then the remaining paragraphs will not be tagged.
+ # Regardless of indentation settings, a blank line will be inserted
+ # between all paragraphs when <tt>#tag_paragraph</tt> is +true+.
+ #
+ # *Default*:: <tt>[]</tt>
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
+ attr_accessor :tag_text
+
+ # Indicates whether or not the non-breaking space feature should be
+ # used.
+ #
+ # *Default*:: +false+
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
+ attr_accessor :nobreak
+
+ # A hash which holds the regular expressions on which spaces should not
+ # be broken. The hash is set up such that the key is the first word and
+ # the value is the second word.
+ #
+ # For example, if +nobreak_regex+ contains the following hash:
+ #
+ # { '^Mrs?\.$' => '\S+$', '^\S+$' => '^(?:S|J)r\.$'}
+ #
+ # Then "Mr. Jones", "Mrs. Jones", and "Jones Jr." would not be broken.
+ # If this simple matching algorithm indicates that there should not be a
+ # break at the current end of line, then a backtrack is done until there
+ # are two words on which line breaking is permitted. If two such words
+ # are not found, then the end of the line will be broken *regardless*.
+ # If there is a single word on the current line, then no backtrack is
+ # done and the word is stuck on the end.
+ #
+ # *Default*:: <tt>{}</tt>
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
+ attr_accessor :nobreak_regex
+
+ # Indicates the number of spaces that a single tab represents.
+ #
+ # *Default*:: <tt>8</tt>
+ # <b>Used in</b>:: <tt>#expand</tt>, <tt>#unexpand</tt>,
+ # <tt>#paragraphs</tt>
+ attr_reader :tabstop
+
+ # Indicates the number of spaces that a single tab represents.
+ #
+ # *Default*:: <tt>8</tt>
+ # <b>Used in</b>:: <tt>#expand</tt>, <tt>#unexpand</tt>,
+ # <tt>#paragraphs</tt>
+ def tabstop=(t)
+ @tabstop = posint(t)
+ end
+
+ # Specifies the format style. Allowable values are:
+ # [+LEFT_ALIGN+] Left justified, ragged right.
+ # |A paragraph that is|
+ # |left aligned.|
+ # [+RIGHT_ALIGN+] Right justified, ragged left.
+ # |A paragraph that is|
+ # | right aligned.|
+ # [+RIGHT_FILL+] Left justified, right ragged, filled to width by
+ # spaces. (Essentially the same as +LEFT_ALIGN+ except
+ # that lines are padded on the right.)
+ # |A paragraph that is|
+ # |left aligned. |
+ # [+JUSTIFY+] Fully justified, words filled to width by spaces,
+ # except the last line.
+ # |A paragraph that|
+ # |is justified.|
+ #
+ # *Default*:: <tt>Text::Format::LEFT_ALIGN</tt>
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
+ attr_reader :format_style
+
+ # Specifies the format style. Allowable values are:
+ # [+LEFT_ALIGN+] Left justified, ragged right.
+ # |A paragraph that is|
+ # |left aligned.|
+ # [+RIGHT_ALIGN+] Right justified, ragged left.
+ # |A paragraph that is|
+ # | right aligned.|
+ # [+RIGHT_FILL+] Left justified, right ragged, filled to width by
+ # spaces. (Essentially the same as +LEFT_ALIGN+ except
+ # that lines are padded on the right.)
+ # |A paragraph that is|
+ # |left aligned. |
+ # [+JUSTIFY+] Fully justified, words filled to width by spaces.
+ # |A paragraph that|
+ # |is justified.|
+ #
+ # *Default*:: <tt>Text::Format::LEFT_ALIGN</tt>
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
+ def format_style=(fs)
+ raise ArgumentError, "Invalid value provided for format_style." if ((fs < LEFT_ALIGN) || (fs > JUSTIFY))
+ @format_style = fs
+ end
+
+ # Indicates that the format style is left alignment.
+ #
+ # *Default*:: +true+
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
+ def left_align?
+ return @format_style == LEFT_ALIGN
+ end
+
+ # Indicates that the format style is right alignment.
+ #
+ # *Default*:: +false+
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
+ def right_align?
+ return @format_style == RIGHT_ALIGN
+ end
+
+ # Indicates that the format style is right fill.
+ #
+ # *Default*:: +false+
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
+ def right_fill?
+ return @format_style == RIGHT_FILL
+ end
+
+ # Indicates that the format style is full justification.
+ #
+ # *Default*:: +false+
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
+ def justify?
+ return @format_style == JUSTIFY
+ end
+
+ # The default implementation of #hyphenate_to implements
+ # SPLIT_CONTINUATION.
+ def hyphenate_to(word, size)
+ [word[0 .. (size - 2)] + "\\", word[(size - 1) .. -1]]
+ end
+
+ private
+ def __do_split_word(word, size) #:nodoc:
+ [word[0 .. (size - 1)], word[size .. -1]]
+ end
+
+ def __format(to_wrap) #:nodoc:
+ words = to_wrap.split(/\s+/).compact
+ words.shift if words[0].nil? or words[0].empty?
+ to_wrap = []
+
+ abbrev = false
+ width = @columns - @first_indent - @left_margin - @right_margin
+ indent_str = ' ' * @first_indent
+ first_line = true
+ line = words.shift
+ abbrev = __is_abbrev(line) unless line.nil? || line.empty?
+
+ while w = words.shift
+ if (w.size + line.size < (width - 1)) ||
+ ((line !~ LEQ_RE || abbrev) && (w.size + line.size < width))
+ line << " " if (line =~ LEQ_RE) && (not abbrev)
+ line << " #{w}"
+ else
+ line, w = __do_break(line, w) if @nobreak
+ line, w = __do_hyphenate(line, w, width) if @hard_margins
+ if w.index(/\s+/)
+ w, *w2 = w.split(/\s+/)
+ words.unshift(w2)
+ words.flatten!
+ end
+ to_wrap << __make_line(line, indent_str, width, w.nil?) unless line.nil?
+ if first_line
+ first_line = false
+ width = @columns - @body_indent - @left_margin - @right_margin
+ indent_str = ' ' * @body_indent
+ end
+ line = w
+ end
+
+ abbrev = __is_abbrev(w) unless w.nil?
+ end
+
+ loop do
+ break if line.nil? or line.empty?
+ line, w = __do_hyphenate(line, w, width) if @hard_margins
+ to_wrap << __make_line(line, indent_str, width, w.nil?)
+ line = w
+ end
+
+ if (@tag_paragraph && (to_wrap.size > 0)) then
+ clr = %r{`(\w+)'}.match([caller(1)].flatten[0])[1]
+ clr = "" if clr.nil?
+
+ if ((not @tag_text[0].nil?) && (@tag_cur.size < 1) &&
+ (clr != "__paragraphs")) then
+ @tag_cur = @tag_text[0]
+ end
+
+ fchar = /(\S)/.match(to_wrap[0])[1]
+ white = to_wrap[0].index(fchar)
+ if ((white - @left_margin - 1) > @tag_cur.size) then
+ white = @tag_cur.size + @left_margin
+ to_wrap[0].gsub!(/^ {#{white}}/, "#{' ' * @left_margin}#{@tag_cur}")
+ else
+ to_wrap.unshift("#{' ' * @left_margin}#{@tag_cur}\n")
+ end
+ end
+ to_wrap.join('')
+ end
+
+ # format lines in text into paragraphs with each element of @wrap a
+ # paragraph; uses Text::Format.format for the formatting
+ def __paragraphs(to_wrap) #:nodoc:
+ if ((@first_indent == @body_indent) || @tag_paragraph) then
+ p_end = "\n"
+ else
+ p_end = ''
+ end
+
+ cnt = 0
+ ret = []
+ to_wrap.each do |tw|
+ @tag_cur = @tag_text[cnt] if @tag_paragraph
+ @tag_cur = '' if @tag_cur.nil?
+ line = __format(tw)
+ ret << "#{line}#{p_end}" if (not line.nil?) && (line.size > 0)
+ cnt += 1
+ end
+
+ ret[-1].chomp! unless ret.empty?
+ ret.join('')
+ end
+
+ # center text using spaces on left side to pad it out empty lines
+ # are preserved
+ def __center(to_center) #:nodoc:
+ tabs = 0
+ width = @columns - @left_margin - @right_margin
+ centered = []
+ to_center.each do |tc|
+ s = tc.strip
+ tabs = s.count("\t")
+ tabs = 0 if tabs.nil?
+ ct = ((width - s.size - (tabs * @tabstop) + tabs) / 2)
+ ct = (width - @left_margin - @right_margin) - ct
+ centered << "#{s.rjust(ct)}\n"
+ end
+ centered.join('')
+ end
+
+ # expand tabs to spaces should be similar to Text::Tabs::expand
+ def __expand(to_expand) #:nodoc:
+ expanded = []
+ to_expand.split("\n").each { |te| expanded << te.gsub(/\t/, ' ' * @tabstop) }
+ expanded.join('')
+ end
+
+ def __unexpand(to_unexpand) #:nodoc:
+ unexpanded = []
+ to_unexpand.split("\n").each { |tu| unexpanded << tu.gsub(/ {#{@tabstop}}/, "\t") }
+ unexpanded.join('')
+ end
+
+ def __is_abbrev(word) #:nodoc:
+ # remove period if there is one.
+ w = word.gsub(/\.$/, '') unless word.nil?
+ return true if (!@extra_space || ABBREV.include?(w) || @abbreviations.include?(w))
+ false
+ end
+
+ def __make_line(line, indent, width, last = false) #:nodoc:
+ lmargin = " " * @left_margin
+ fill = " " * (width - line.size) if right_fill? && (line.size <= width)
+
+ if (justify? && ((not line.nil?) && (not line.empty?)) && line =~ /\S+\s+\S+/ && !last)
+ spaces = width - line.size
+ words = line.split(/(\s+)/)
+ ws = spaces / (words.size / 2)
+ spaces = spaces % (words.size / 2) if ws > 0
+ words.reverse.each do |rw|
+ next if (rw =~ /^\S/)
+ rw.sub!(/^/, " " * ws)
+ next unless (spaces > 0)
+ rw.sub!(/^/, " ")
+ spaces -= 1
+ end
+ line = words.join('')
+ end
+ line = "#{lmargin}#{indent}#{line}#{fill}\n" unless line.nil?
+ if right_align? && (not line.nil?)
+ line.sub(/^/, " " * (@columns - @right_margin - (line.size - 1)))
+ else
+ line
+ end
+ end
+
+ def __do_hyphenate(line, next_line, width) #:nodoc:
+ rline = line.dup rescue line
+ rnext = next_line.dup rescue next_line
+ loop do
+ if rline.size == width
+ break
+ elsif rline.size > width
+ words = rline.strip.split(/\s+/)
+ word = words[-1].dup
+ size = width - rline.size + word.size
+ if (size <= 0)
+ words[-1] = nil
+ rline = words.join(' ').strip
+ rnext = "#{word} #{rnext}".strip
+ next
+ end
+
+ first = rest = nil
+
+ if ((@split_rules & SPLIT_HYPHENATION) != 0)
+ if @hyphenator_arity == 2
+ first, rest = @hyphenator.hyphenate_to(word, size)
+ else
+ first, rest = @hyphenator.hyphenate_to(word, size, self)
+ end
+ end
+
+ if ((@split_rules & SPLIT_CONTINUATION) != 0) and first.nil?
+ first, rest = self.hyphenate_to(word, size)
+ end
+
+ if ((@split_rules & SPLIT_FIXED) != 0) and first.nil?
+ first.nil? or @split_rules == SPLIT_FIXED
+ first, rest = __do_split_word(word, size)
+ end
+
+ if first.nil?
+ words[-1] = nil
+ rest = word
+ else
+ words[-1] = first
+ @split_words << SplitWord.new(word, first, rest)
+ end
+ rline = words.join(' ').strip
+ rnext = "#{rest} #{rnext}".strip
+ break
+ else
+ break if rnext.nil? or rnext.empty? or rline.nil? or rline.empty?
+ words = rnext.split(/\s+/)
+ word = words.shift
+ size = width - rline.size - 1
+
+ if (size <= 0)
+ rnext = "#{word} #{words.join(' ')}".strip
+ break
+ end
+
+ first = rest = nil
+
+ if ((@split_rules & SPLIT_HYPHENATION) != 0)
+ if @hyphenator_arity == 2
+ first, rest = @hyphenator.hyphenate_to(word, size)
+ else
+ first, rest = @hyphenator.hyphenate_to(word, size, self)
+ end
+ end
+
+ first, rest = self.hyphenate_to(word, size) if ((@split_rules & SPLIT_CONTINUATION) != 0) and first.nil?
+
+ first, rest = __do_split_word(word, size) if ((@split_rules & SPLIT_FIXED) != 0) and first.nil?
+
+ if (rline.size + (first ? first.size : 0)) < width
+ @split_words << SplitWord.new(word, first, rest)
+ rline = "#{rline} #{first}".strip
+ rnext = "#{rest} #{words.join(' ')}".strip
+ end
+ break
+ end
+ end
+ [rline, rnext]
+ end
+
+ def __do_break(line, next_line) #:nodoc:
+ no_brk = false
+ words = []
+ words = line.split(/\s+/) unless line.nil?
+ last_word = words[-1]
+
+ @nobreak_regex.each { |k, v| no_brk = ((last_word =~ /#{k}/) and (next_line =~ /#{v}/)) }
+
+ if no_brk && words.size > 1
+ i = words.size
+ while i > 0
+ no_brk = false
+ @nobreak_regex.each { |k, v| no_brk = ((words[i + 1] =~ /#{k}/) && (words[i] =~ /#{v}/)) }
+ i -= 1
+ break if not no_brk
+ end
+ if i > 0
+ l = brk_re(i).match(line)
+ line.sub!(brk_re(i), l[1])
+ next_line = "#{l[2]} #{next_line}"
+ line.sub!(/\s+$/, '')
+ end
+ end
+ [line, next_line]
+ end
+
+ def __create(arg = nil, &block) #:nodoc:
+ # Format::Text.new(text-to-wrap)
+ @text = arg unless arg.nil?
+ # Defaults
+ @columns = 72
+ @tabstop = 8
+ @first_indent = 4
+ @body_indent = 0
+ @format_style = LEFT_ALIGN
+ @left_margin = 0
+ @right_margin = 0
+ @extra_space = false
+ @text = Array.new if @text.nil?
+ @tag_paragraph = false
+ @tag_text = Array.new
+ @tag_cur = ""
+ @abbreviations = Array.new
+ @nobreak = false
+ @nobreak_regex = Hash.new
+ @split_words = Array.new
+ @hard_margins = false
+ @split_rules = SPLIT_FIXED
+ @hyphenator = self
+ @hyphenator_arity = self.method(:hyphenate_to).arity
+
+ instance_eval(&block) unless block.nil?
+ end
+
+ public
+ # Formats text into a nice paragraph format. The text is separated
+ # into words and then reassembled a word at a time using the settings
+ # of this Format object. If a word is larger than the number of
+ # columns available for formatting, then that word will appear on the
+ # line by itself.
+ #
+ # If +to_wrap+ is +nil+, then the value of <tt>#text</tt> will be
+ # worked on.
+ def format(to_wrap = nil)
+ to_wrap = @text if to_wrap.nil?
+ if to_wrap.class == Array
+ __format(to_wrap[0])
+ else
+ __format(to_wrap)
+ end
+ end
+
+ # Considers each element of text (provided or internal) as a paragraph.
+ # If <tt>#first_indent</tt> is the same as <tt>#body_indent</tt>, then
+ # paragraphs will be separated by a single empty line in the result;
+ # otherwise, the paragraphs will follow immediately after each other.
+ # Uses <tt>#format</tt> to do the heavy lifting.
+ def paragraphs(to_wrap = nil)
+ to_wrap = @text if to_wrap.nil?
+ __paragraphs([to_wrap].flatten)
+ end
+
+ # Centers the text, preserving empty lines and tabs.
+ def center(to_center = nil)
+ to_center = @text if to_center.nil?
+ __center([to_center].flatten)
+ end
+
+ # Replaces all tab characters in the text with <tt>#tabstop</tt> spaces.
+ def expand(to_expand = nil)
+ to_expand = @text if to_expand.nil?
+ if to_expand.class == Array
+ to_expand.collect { |te| __expand(te) }
+ else
+ __expand(to_expand)
+ end
+ end
+
+ # Replaces all occurrences of <tt>#tabstop</tt> consecutive spaces
+ # with a tab character.
+ def unexpand(to_unexpand = nil)
+ to_unexpand = @text if to_unexpand.nil?
+ if to_unexpand.class == Array
+ to_unexpand.collect { |te| v << __unexpand(te) }
+ else
+ __unexpand(to_unexpand)
+ end
+ end
+
+ # This constructor takes advantage of a technique for Ruby object
+ # construction introduced by Andy Hunt and Dave Thomas (see reference),
+ # where optional values are set using commands in a block.
+ #
+ # Text::Format.new {
+ # columns = 72
+ # left_margin = 0
+ # right_margin = 0
+ # first_indent = 4
+ # body_indent = 0
+ # format_style = Text::Format::LEFT_ALIGN
+ # extra_space = false
+ # abbreviations = {}
+ # tag_paragraph = false
+ # tag_text = []
+ # nobreak = false
+ # nobreak_regex = {}
+ # tabstop = 8
+ # text = nil
+ # }
+ #
+ # As shown above, +arg+ is optional. If +arg+ is specified and is a
+ # +String+, then arg is used as the default value of <tt>#text</tt>.
+ # Alternately, an existing Text::Format object can be used or a Hash can
+ # be used. With all forms, a block can be specified.
+ #
+ # *Reference*:: "Object Construction and Blocks"
+ # <http://www.pragmaticprogrammer.com/ruby/articles/insteval.html>
+ #
+ def initialize(arg = nil, &block)
+ case arg
+ when Text::Format
+ __create(arg.text) do
+ @columns = arg.columns
+ @tabstop = arg.tabstop
+ @first_indent = arg.first_indent
+ @body_indent = arg.body_indent
+ @format_style = arg.format_style
+ @left_margin = arg.left_margin
+ @right_margin = arg.right_margin
+ @extra_space = arg.extra_space
+ @tag_paragraph = arg.tag_paragraph
+ @tag_text = arg.tag_text
+ @abbreviations = arg.abbreviations
+ @nobreak = arg.nobreak
+ @nobreak_regex = arg.nobreak_regex
+ @text = arg.text
+ @hard_margins = arg.hard_margins
+ @split_words = arg.split_words
+ @split_rules = arg.split_rules
+ @hyphenator = arg.hyphenator
+ end
+ instance_eval(&block) unless block.nil?
+ when Hash
+ __create do
+ @columns = arg[:columns] || arg['columns'] || @columns
+ @tabstop = arg[:tabstop] || arg['tabstop'] || @tabstop
+ @first_indent = arg[:first_indent] || arg['first_indent'] || @first_indent
+ @body_indent = arg[:body_indent] || arg['body_indent'] || @body_indent
+ @format_style = arg[:format_style] || arg['format_style'] || @format_style
+ @left_margin = arg[:left_margin] || arg['left_margin'] || @left_margin
+ @right_margin = arg[:right_margin] || arg['right_margin'] || @right_margin
+ @extra_space = arg[:extra_space] || arg['extra_space'] || @extra_space
+ @text = arg[:text] || arg['text'] || @text
+ @tag_paragraph = arg[:tag_paragraph] || arg['tag_paragraph'] || @tag_paragraph
+ @tag_text = arg[:tag_text] || arg['tag_text'] || @tag_text
+ @abbreviations = arg[:abbreviations] || arg['abbreviations'] || @abbreviations
+ @nobreak = arg[:nobreak] || arg['nobreak'] || @nobreak
+ @nobreak_regex = arg[:nobreak_regex] || arg['nobreak_regex'] || @nobreak_regex
+ @hard_margins = arg[:hard_margins] || arg['hard_margins'] || @hard_margins
+ @split_rules = arg[:split_rules] || arg['split_rules'] || @split_rules
+ @hyphenator = arg[:hyphenator] || arg['hyphenator'] || @hyphenator
+ end
+ instance_eval(&block) unless block.nil?
+ when String
+ __create(arg, &block)
+ when NilClass
+ __create(&block)
+ else
+ raise TypeError
+ end
+ end
+ end
+end
+
+if __FILE__ == $0
+ require 'test/unit'
+
+ class TestText__Format < Test::Unit::TestCase #:nodoc:
+ attr_accessor :format_o
+
+ GETTYSBURG = <<-'EOS'
+ Four score and seven years ago our fathers brought forth on this
+ continent a new nation, conceived in liberty and dedicated to the
+ proposition that all men are created equal. Now we are engaged in
+ a great civil war, testing whether that nation or any nation so
+ conceived and so dedicated can long endure. We are met on a great
+ battlefield of that war. We have come to dedicate a portion of
+ that field as a final resting-place for those who here gave their
+ lives that that nation might live. It is altogether fitting and
+ proper that we should do this. But in a larger sense, we cannot
+ dedicate, we cannot consecrate, we cannot hallow this ground.
+ The brave men, living and dead who struggled here have consecrated
+ it far above our poor power to add or detract. The world will
+ little note nor long remember what we say here, but it can never
+ forget what they did here. It is for us the living rather to be
+ dedicated here to the unfinished work which they who fought here
+ have thus far so nobly advanced. It is rather for us to be here
+ dedicated to the great task remaining before us--that from these
+ honored dead we take increased devotion to that cause for which
+ they gave the last full measure of devotion--that we here highly
+ resolve that these dead shall not have died in vain, that this
+ nation under God shall have a new birth of freedom, and that
+ government of the people, by the people, for the people shall
+ not perish from the earth.
+
+ -- Pres. Abraham Lincoln, 19 November 1863
+ EOS
+
+ FIVE_COL = "Four \nscore\nand s\neven \nyears\nago o\nur fa\nthers\nbroug\nht fo\nrth o\nn thi\ns con\ntinen\nt a n\new na\ntion,\nconce\nived \nin li\nberty\nand d\nedica\nted t\no the\npropo\nsitio\nn tha\nt all\nmen a\nre cr\neated\nequal\n. Now\nwe ar\ne eng\naged \nin a \ngreat\ncivil\nwar, \ntesti\nng wh\nether\nthat \nnatio\nn or \nany n\nation\nso co\nnceiv\ned an\nd so \ndedic\nated \ncan l\nong e\nndure\n. We \nare m\net on\na gre\nat ba\nttlef\nield \nof th\nat wa\nr. We\nhave \ncome \nto de\ndicat\ne a p\nortio\nn of \nthat \nfield\nas a \nfinal\nresti\nng-pl\nace f\nor th\nose w\nho he\nre ga\nve th\neir l\nives \nthat \nthat \nnatio\nn mig\nht li\nve. I\nt is \naltog\nether\nfitti\nng an\nd pro\nper t\nhat w\ne sho\nuld d\no thi\ns. Bu\nt in \na lar\nger s\nense,\nwe ca\nnnot \ndedic\nate, \nwe ca\nnnot \nconse\ncrate\n, we \ncanno\nt hal\nlow t\nhis g\nround\n. The\nbrave\nmen, \nlivin\ng and\ndead \nwho s\ntrugg\nled h\nere h\nave c\nonsec\nrated\nit fa\nr abo\nve ou\nr poo\nr pow\ner to\nadd o\nr det\nract.\nThe w\norld \nwill \nlittl\ne not\ne nor\nlong \nremem\nber w\nhat w\ne say\nhere,\nbut i\nt can\nnever\nforge\nt wha\nt the\ny did\nhere.\nIt is\nfor u\ns the\nlivin\ng rat\nher t\no be \ndedic\nated \nhere \nto th\ne unf\ninish\ned wo\nrk wh\nich t\nhey w\nho fo\nught \nhere \nhave \nthus \nfar s\no nob\nly ad\nvance\nd. It\nis ra\nther \nfor u\ns to \nbe he\nre de\ndicat\ned to\nthe g\nreat \ntask \nremai\nning \nbefor\ne us-\n-that\nfrom \nthese\nhonor\ned de\nad we\ntake \nincre\nased \ndevot\nion t\no tha\nt cau\nse fo\nr whi\nch th\ney ga\nve th\ne las\nt ful\nl mea\nsure \nof de\nvotio\nn--th\nat we\nhere \nhighl\ny res\nolve \nthat \nthese\ndead \nshall\nnot h\nave d\nied i\nn vai\nn, th\nat th\nis na\ntion \nunder\nGod s\nhall \nhave \na new\nbirth\nof fr\needom\n, and\nthat \ngover\nnment\nof th\ne peo\nple, \nby th\ne peo\nple, \nfor t\nhe pe\nople \nshall\nnot p\nerish\nfrom \nthe e\narth.\n-- Pr\nes. A\nbraha\nm Lin\ncoln,\n19 No\nvembe\nr 186\n3 \n"
+
+ FIVE_CNT = "Four \nscore\nand \nseven\nyears\nago \nour \nfath\\\ners \nbrou\\\nght \nforth\non t\\\nhis \ncont\\\ninent\na new\nnati\\\non, \nconc\\\neived\nin l\\\niber\\\nty a\\\nnd d\\\nedic\\\nated \nto t\\\nhe p\\\nropo\\\nsiti\\\non t\\\nhat \nall \nmen \nare \ncrea\\\nted \nequa\\\nl. N\\\now we\nare \nenga\\\nged \nin a \ngreat\ncivil\nwar, \ntest\\\ning \nwhet\\\nher \nthat \nnati\\\non or\nany \nnati\\\non so\nconc\\\neived\nand \nso d\\\nedic\\\nated \ncan \nlong \nendu\\\nre. \nWe a\\\nre m\\\net on\na gr\\\neat \nbatt\\\nlefi\\\neld \nof t\\\nhat \nwar. \nWe h\\\nave \ncome \nto d\\\nedic\\\nate a\nport\\\nion \nof t\\\nhat \nfield\nas a \nfinal\nrest\\\ning-\\\nplace\nfor \nthose\nwho \nhere \ngave \ntheir\nlives\nthat \nthat \nnati\\\non m\\\night \nlive.\nIt is\nalto\\\ngeth\\\ner f\\\nitti\\\nng a\\\nnd p\\\nroper\nthat \nwe s\\\nhould\ndo t\\\nhis. \nBut \nin a \nlarg\\\ner s\\\nense,\nwe c\\\nannot\ndedi\\\ncate,\nwe c\\\nannot\ncons\\\necra\\\nte, \nwe c\\\nannot\nhall\\\now t\\\nhis \ngrou\\\nnd. \nThe \nbrave\nmen, \nlivi\\\nng a\\\nnd d\\\nead \nwho \nstru\\\nggled\nhere \nhave \ncons\\\necra\\\nted \nit f\\\nar a\\\nbove \nour \npoor \npower\nto a\\\ndd or\ndetr\\\nact. \nThe \nworld\nwill \nlitt\\\nle n\\\note \nnor \nlong \nreme\\\nmber \nwhat \nwe s\\\nay h\\\nere, \nbut \nit c\\\nan n\\\never \nforg\\\net w\\\nhat \nthey \ndid \nhere.\nIt is\nfor \nus t\\\nhe l\\\niving\nrath\\\ner to\nbe d\\\nedic\\\nated \nhere \nto t\\\nhe u\\\nnfin\\\nished\nwork \nwhich\nthey \nwho \nfoug\\\nht h\\\nere \nhave \nthus \nfar \nso n\\\nobly \nadva\\\nnced.\nIt is\nrath\\\ner f\\\nor us\nto be\nhere \ndedi\\\ncated\nto t\\\nhe g\\\nreat \ntask \nrema\\\nining\nbefo\\\nre u\\\ns--t\\\nhat \nfrom \nthese\nhono\\\nred \ndead \nwe t\\\nake \nincr\\\neased\ndevo\\\ntion \nto t\\\nhat \ncause\nfor \nwhich\nthey \ngave \nthe \nlast \nfull \nmeas\\\nure \nof d\\\nevot\\\nion-\\\n-that\nwe h\\\nere \nhigh\\\nly r\\\nesol\\\nve t\\\nhat \nthese\ndead \nshall\nnot \nhave \ndied \nin v\\\nain, \nthat \nthis \nnati\\\non u\\\nnder \nGod \nshall\nhave \na new\nbirth\nof f\\\nreed\\\nom, \nand \nthat \ngove\\\nrnme\\\nnt of\nthe \npeop\\\nle, \nby t\\\nhe p\\\neopl\\\ne, f\\\nor t\\\nhe p\\\neople\nshall\nnot \nperi\\\nsh f\\\nrom \nthe \neart\\\nh. --\nPres.\nAbra\\\nham \nLinc\\\noln, \n19 N\\\novem\\\nber \n1863 \n"
+
+ # Tests both abbreviations and abbreviations=
+ def test_abbreviations
+ abbr = [" Pres. Abraham Lincoln\n", " Pres. Abraham Lincoln\n"]
+ assert_nothing_raised { @format_o = Text::Format.new }
+ assert_equal([], @format_o.abbreviations)
+ assert_nothing_raised { @format_o.abbreviations = [ 'foo', 'bar' ] }
+ assert_equal([ 'foo', 'bar' ], @format_o.abbreviations)
+ assert_equal(abbr[0], @format_o.format(abbr[0]))
+ assert_nothing_raised { @format_o.extra_space = true }
+ assert_equal(abbr[1], @format_o.format(abbr[0]))
+ assert_nothing_raised { @format_o.abbreviations = [ "Pres" ] }
+ assert_equal([ "Pres" ], @format_o.abbreviations)
+ assert_equal(abbr[0], @format_o.format(abbr[0]))
+ assert_nothing_raised { @format_o.extra_space = false }
+ assert_equal(abbr[0], @format_o.format(abbr[0]))
+ end
+
+ # Tests both body_indent and body_indent=
+ def test_body_indent
+ assert_nothing_raised { @format_o = Text::Format.new }
+ assert_equal(0, @format_o.body_indent)
+ assert_nothing_raised { @format_o.body_indent = 7 }
+ assert_equal(7, @format_o.body_indent)
+ assert_nothing_raised { @format_o.body_indent = -3 }
+ assert_equal(3, @format_o.body_indent)
+ assert_nothing_raised { @format_o.body_indent = "9" }
+ assert_equal(9, @format_o.body_indent)
+ assert_nothing_raised { @format_o.body_indent = "-2" }
+ assert_equal(2, @format_o.body_indent)
+ assert_match(/^ [^ ]/, @format_o.format(GETTYSBURG).split("\n")[1])
+ end
+
+ # Tests both columns and columns=
+ def test_columns
+ assert_nothing_raised { @format_o = Text::Format.new }
+ assert_equal(72, @format_o.columns)
+ assert_nothing_raised { @format_o.columns = 7 }
+ assert_equal(7, @format_o.columns)
+ assert_nothing_raised { @format_o.columns = -3 }
+ assert_equal(3, @format_o.columns)
+ assert_nothing_raised { @format_o.columns = "9" }
+ assert_equal(9, @format_o.columns)
+ assert_nothing_raised { @format_o.columns = "-2" }
+ assert_equal(2, @format_o.columns)
+ assert_nothing_raised { @format_o.columns = 40 }
+ assert_equal(40, @format_o.columns)
+ assert_match(/this continent$/,
+ @format_o.format(GETTYSBURG).split("\n")[1])
+ end
+
+ # Tests both extra_space and extra_space=
+ def test_extra_space
+ assert_nothing_raised { @format_o = Text::Format.new }
+ assert(!@format_o.extra_space)
+ assert_nothing_raised { @format_o.extra_space = true }
+ assert(@format_o.extra_space)
+ # The behaviour of extra_space is tested in test_abbreviations. There
+ # is no need to reproduce it here.
+ end
+
+ # Tests both first_indent and first_indent=
+ def test_first_indent
+ assert_nothing_raised { @format_o = Text::Format.new }
+ assert_equal(4, @format_o.first_indent)
+ assert_nothing_raised { @format_o.first_indent = 7 }
+ assert_equal(7, @format_o.first_indent)
+ assert_nothing_raised { @format_o.first_indent = -3 }
+ assert_equal(3, @format_o.first_indent)
+ assert_nothing_raised { @format_o.first_indent = "9" }
+ assert_equal(9, @format_o.first_indent)
+ assert_nothing_raised { @format_o.first_indent = "-2" }
+ assert_equal(2, @format_o.first_indent)
+ assert_match(/^ [^ ]/, @format_o.format(GETTYSBURG).split("\n")[0])
+ end
+
+ def test_format_style
+ assert_nothing_raised { @format_o = Text::Format.new }
+ assert_equal(Text::Format::LEFT_ALIGN, @format_o.format_style)
+ assert_match(/^November 1863$/,
+ @format_o.format(GETTYSBURG).split("\n")[-1])
+ assert_nothing_raised {
+ @format_o.format_style = Text::Format::RIGHT_ALIGN
+ }
+ assert_equal(Text::Format::RIGHT_ALIGN, @format_o.format_style)
+ assert_match(/^ +November 1863$/,
+ @format_o.format(GETTYSBURG).split("\n")[-1])
+ assert_nothing_raised {
+ @format_o.format_style = Text::Format::RIGHT_FILL
+ }
+ assert_equal(Text::Format::RIGHT_FILL, @format_o.format_style)
+ assert_match(/^November 1863 +$/,
+ @format_o.format(GETTYSBURG).split("\n")[-1])
+ assert_nothing_raised { @format_o.format_style = Text::Format::JUSTIFY }
+ assert_equal(Text::Format::JUSTIFY, @format_o.format_style)
+ assert_match(/^of freedom, and that government of the people, by the people, for the$/,
+ @format_o.format(GETTYSBURG).split("\n")[-3])
+ assert_raises(ArgumentError) { @format_o.format_style = 33 }
+ end
+
+ def test_tag_paragraph
+ assert_nothing_raised { @format_o = Text::Format.new }
+ assert(!@format_o.tag_paragraph)
+ assert_nothing_raised { @format_o.tag_paragraph = true }
+ assert(@format_o.tag_paragraph)
+ assert_not_equal(@format_o.paragraphs([GETTYSBURG, GETTYSBURG]),
+ Text::Format.new.paragraphs([GETTYSBURG, GETTYSBURG]))
+ end
+
+ def test_tag_text
+ assert_nothing_raised { @format_o = Text::Format.new }
+ assert_equal([], @format_o.tag_text)
+ assert_equal(@format_o.format(GETTYSBURG),
+ Text::Format.new.format(GETTYSBURG))
+ assert_nothing_raised {
+ @format_o.tag_paragraph = true
+ @format_o.tag_text = ["Gettysburg Address", "---"]
+ }
+ assert_not_equal(@format_o.format(GETTYSBURG),
+ Text::Format.new.format(GETTYSBURG))
+ assert_not_equal(@format_o.paragraphs([GETTYSBURG, GETTYSBURG]),
+ Text::Format.new.paragraphs([GETTYSBURG, GETTYSBURG]))
+ assert_not_equal(@format_o.paragraphs([GETTYSBURG, GETTYSBURG,
+ GETTYSBURG]),
+ Text::Format.new.paragraphs([GETTYSBURG, GETTYSBURG,
+ GETTYSBURG]))
+ end
+
+ def test_justify?
+ assert_nothing_raised { @format_o = Text::Format.new }
+ assert(!@format_o.justify?)
+ assert_nothing_raised {
+ @format_o.format_style = Text::Format::RIGHT_ALIGN
+ }
+ assert(!@format_o.justify?)
+ assert_nothing_raised {
+ @format_o.format_style = Text::Format::RIGHT_FILL
+ }
+ assert(!@format_o.justify?)
+ assert_nothing_raised {
+ @format_o.format_style = Text::Format::JUSTIFY
+ }
+ assert(@format_o.justify?)
+ # The format testing is done in test_format_style
+ end
+
+ def test_left_align?
+ assert_nothing_raised { @format_o = Text::Format.new }
+ assert(@format_o.left_align?)
+ assert_nothing_raised {
+ @format_o.format_style = Text::Format::RIGHT_ALIGN
+ }
+ assert(!@format_o.left_align?)
+ assert_nothing_raised {
+ @format_o.format_style = Text::Format::RIGHT_FILL
+ }
+ assert(!@format_o.left_align?)
+ assert_nothing_raised { @format_o.format_style = Text::Format::JUSTIFY }
+ assert(!@format_o.left_align?)
+ # The format testing is done in test_format_style
+ end
+
+ def test_left_margin
+ assert_nothing_raised { @format_o = Text::Format.new }
+ assert_equal(0, @format_o.left_margin)
+ assert_nothing_raised { @format_o.left_margin = -3 }
+ assert_equal(3, @format_o.left_margin)
+ assert_nothing_raised { @format_o.left_margin = "9" }
+ assert_equal(9, @format_o.left_margin)
+ assert_nothing_raised { @format_o.left_margin = "-2" }
+ assert_equal(2, @format_o.left_margin)
+ assert_nothing_raised { @format_o.left_margin = 7 }
+ assert_equal(7, @format_o.left_margin)
+ assert_nothing_raised {
+ ft = @format_o.format(GETTYSBURG).split("\n")
+ assert_match(/^ {11}Four score/, ft[0])
+ assert_match(/^ {7}November/, ft[-1])
+ }
+ end
+
+ def test_hard_margins
+ assert_nothing_raised { @format_o = Text::Format.new }
+ assert(!@format_o.hard_margins)
+ assert_nothing_raised {
+ @format_o.hard_margins = true
+ @format_o.columns = 5
+ @format_o.first_indent = 0
+ @format_o.format_style = Text::Format::RIGHT_FILL
+ }
+ assert(@format_o.hard_margins)
+ assert_equal(FIVE_COL, @format_o.format(GETTYSBURG))
+ assert_nothing_raised {
+ @format_o.split_rules |= Text::Format::SPLIT_CONTINUATION
+ assert_equal(Text::Format::SPLIT_CONTINUATION_FIXED,
+ @format_o.split_rules)
+ }
+ assert_equal(FIVE_CNT, @format_o.format(GETTYSBURG))
+ end
+
+ # Tests both nobreak and nobreak_regex, since one is only useful
+ # with the other.
+ def test_nobreak
+ assert_nothing_raised { @format_o = Text::Format.new }
+ assert(!@format_o.nobreak)
+ assert(@format_o.nobreak_regex.empty?)
+ assert_nothing_raised {
+ @format_o.nobreak = true
+ @format_o.nobreak_regex = { '^this$' => '^continent$' }
+ @format_o.columns = 77
+ }
+ assert(@format_o.nobreak)
+ assert_equal({ '^this$' => '^continent$' }, @format_o.nobreak_regex)
+ assert_match(/^this continent/,
+ @format_o.format(GETTYSBURG).split("\n")[1])
+ end
+
+ def test_right_align?
+ assert_nothing_raised { @format_o = Text::Format.new }
+ assert(!@format_o.right_align?)
+ assert_nothing_raised {
+ @format_o.format_style = Text::Format::RIGHT_ALIGN
+ }
+ assert(@format_o.right_align?)
+ assert_nothing_raised {
+ @format_o.format_style = Text::Format::RIGHT_FILL
+ }
+ assert(!@format_o.right_align?)
+ assert_nothing_raised { @format_o.format_style = Text::Format::JUSTIFY }
+ assert(!@format_o.right_align?)
+ # The format testing is done in test_format_style
+ end
+
+ def test_right_fill?
+ assert_nothing_raised { @format_o = Text::Format.new }
+ assert(!@format_o.right_fill?)
+ assert_nothing_raised {
+ @format_o.format_style = Text::Format::RIGHT_ALIGN
+ }
+ assert(!@format_o.right_fill?)
+ assert_nothing_raised {
+ @format_o.format_style = Text::Format::RIGHT_FILL
+ }
+ assert(@format_o.right_fill?)
+ assert_nothing_raised {
+ @format_o.format_style = Text::Format::JUSTIFY
+ }
+ assert(!@format_o.right_fill?)
+ # The format testing is done in test_format_style
+ end
+
+ def test_right_margin
+ assert_nothing_raised { @format_o = Text::Format.new }
+ assert_equal(0, @format_o.right_margin)
+ assert_nothing_raised { @format_o.right_margin = -3 }
+ assert_equal(3, @format_o.right_margin)
+ assert_nothing_raised { @format_o.right_margin = "9" }
+ assert_equal(9, @format_o.right_margin)
+ assert_nothing_raised { @format_o.right_margin = "-2" }
+ assert_equal(2, @format_o.right_margin)
+ assert_nothing_raised { @format_o.right_margin = 7 }
+ assert_equal(7, @format_o.right_margin)
+ assert_nothing_raised {
+ ft = @format_o.format(GETTYSBURG).split("\n")
+ assert_match(/^ {4}Four score.*forth on$/, ft[0])
+ assert_match(/^November/, ft[-1])
+ }
+ end
+
+ def test_tabstop
+ assert_nothing_raised { @format_o = Text::Format.new }
+ assert_equal(8, @format_o.tabstop)
+ assert_nothing_raised { @format_o.tabstop = 7 }
+ assert_equal(7, @format_o.tabstop)
+ assert_nothing_raised { @format_o.tabstop = -3 }
+ assert_equal(3, @format_o.tabstop)
+ assert_nothing_raised { @format_o.tabstop = "9" }
+ assert_equal(9, @format_o.tabstop)
+ assert_nothing_raised { @format_o.tabstop = "-2" }
+ assert_equal(2, @format_o.tabstop)
+ end
+
+ def test_text
+ assert_nothing_raised { @format_o = Text::Format.new }
+ assert_equal([], @format_o.text)
+ assert_nothing_raised { @format_o.text = "Test Text" }
+ assert_equal("Test Text", @format_o.text)
+ assert_nothing_raised { @format_o.text = ["Line 1", "Line 2"] }
+ assert_equal(["Line 1", "Line 2"], @format_o.text)
+ end
+
+ def test_s_new
+ # new(NilClass) { block }
+ assert_nothing_raised do
+ @format_o = Text::Format.new {
+ self.text = "Test 1, 2, 3"
+ }
+ end
+ assert_equal("Test 1, 2, 3", @format_o.text)
+
+ # new(Hash Symbols)
+ assert_nothing_raised { @format_o = Text::Format.new(:columns => 72) }
+ assert_equal(72, @format_o.columns)
+
+ # new(Hash String)
+ assert_nothing_raised { @format_o = Text::Format.new('columns' => 72) }
+ assert_equal(72, @format_o.columns)
+
+ # new(Hash) { block }
+ assert_nothing_raised do
+ @format_o = Text::Format.new('columns' => 80) {
+ self.text = "Test 4, 5, 6"
+ }
+ end
+ assert_equal("Test 4, 5, 6", @format_o.text)
+ assert_equal(80, @format_o.columns)
+
+ # new(Text::Format)
+ assert_nothing_raised do
+ fo = Text::Format.new(@format_o)
+ assert(fo == @format_o)
+ end
+
+ # new(Text::Format) { block }
+ assert_nothing_raised do
+ fo = Text::Format.new(@format_o) { self.columns = 79 }
+ assert(fo != @format_o)
+ end
+
+ # new(String)
+ assert_nothing_raised { @format_o = Text::Format.new("Test A, B, C") }
+ assert_equal("Test A, B, C", @format_o.text)
+
+ # new(String) { block }
+ assert_nothing_raised do
+ @format_o = Text::Format.new("Test X, Y, Z") { self.columns = -5 }
+ end
+ assert_equal("Test X, Y, Z", @format_o.text)
+ assert_equal(5, @format_o.columns)
+ end
+
+ def test_center
+ assert_nothing_raised { @format_o = Text::Format.new }
+ assert_nothing_raised do
+ ct = @format_o.center(GETTYSBURG.split("\n")).split("\n")
+ assert_match(/^ Four score and seven years ago our fathers brought forth on this/, ct[0])
+ assert_match(/^ not perish from the earth./, ct[-3])
+ end
+ end
+
+ def test_expand
+ assert_nothing_raised { @format_o = Text::Format.new }
+ assert_equal(" ", @format_o.expand("\t "))
+ assert_nothing_raised { @format_o.tabstop = 4 }
+ assert_equal(" ", @format_o.expand("\t "))
+ end
+
+ def test_unexpand
+ assert_nothing_raised { @format_o = Text::Format.new }
+ assert_equal("\t ", @format_o.unexpand(" "))
+ assert_nothing_raised { @format_o.tabstop = 4 }
+ assert_equal("\t ", @format_o.unexpand(" "))
+ end
+
+ def test_space_only
+ assert_equal("", Text::Format.new.format(" "))
+ assert_equal("", Text::Format.new.format("\n"))
+ assert_equal("", Text::Format.new.format(" "))
+ assert_equal("", Text::Format.new.format(" \n"))
+ assert_equal("", Text::Format.new.paragraphs("\n"))
+ assert_equal("", Text::Format.new.paragraphs(" "))
+ assert_equal("", Text::Format.new.paragraphs(" "))
+ assert_equal("", Text::Format.new.paragraphs(" \n"))
+ assert_equal("", Text::Format.new.paragraphs(["\n"]))
+ assert_equal("", Text::Format.new.paragraphs([" "]))
+ assert_equal("", Text::Format.new.paragraphs([" "]))
+ assert_equal("", Text::Format.new.paragraphs([" \n"]))
+ end
+
+ def test_splendiferous
+ h = nil
+ test = "This is a splendiferous test"
+ assert_nothing_raised { @format_o = Text::Format.new(:columns => 6, :left_margin => 0, :indent => 0, :first_indent => 0) }
+ assert_match(/^splendiferous$/, @format_o.format(test))
+ assert_nothing_raised { @format_o.hard_margins = true }
+ assert_match(/^lendif$/, @format_o.format(test))
+ assert_nothing_raised { h = Object.new }
+ assert_nothing_raised do
+ @format_o.split_rules = Text::Format::SPLIT_HYPHENATION
+ class << h #:nodoc:
+ def hyphenate_to(word, size)
+ return ["", word] if size < 2
+ [word[0 ... size], word[size .. -1]]
+ end
+ end
+ @format_o.hyphenator = h
+ end
+ assert_match(/^iferou$/, @format_o.format(test))
+ assert_nothing_raised { h = Object.new }
+ assert_nothing_raised do
+ class << h #:nodoc:
+ def hyphenate_to(word, size, formatter)
+ return ["", word] if word.size < formatter.columns
+ [word[0 ... size], word[size .. -1]]
+ end
+ end
+ @format_o.hyphenator = h
+ end
+ assert_match(/^ferous$/, @format_o.format(test))
+ end
+ end
+end
diff --git a/actionmailer/lib/action_mailer/vendor/tmail.rb b/actionmailer/lib/action_mailer/vendor/tmail.rb
new file mode 100755
index 0000000000..013f3020c2
--- /dev/null
+++ b/actionmailer/lib/action_mailer/vendor/tmail.rb
@@ -0,0 +1,4 @@
+require 'tmail/info'
+require 'tmail/mail'
+require 'tmail/mailbox'
+require 'tmail/obsolete'
diff --git a/actionmailer/lib/action_mailer/vendor/tmail/address.rb b/actionmailer/lib/action_mailer/vendor/tmail/address.rb
new file mode 100755
index 0000000000..5367633205
--- /dev/null
+++ b/actionmailer/lib/action_mailer/vendor/tmail/address.rb
@@ -0,0 +1,223 @@
+#
+# address.rb
+#
+# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
+#
+# This program is free software.
+# You can distribute/modify this program under the terms of
+# the GNU Lesser General Public License version 2 or later.
+#
+
+require 'tmail/encode'
+require 'tmail/parser'
+
+
+module TMail
+
+ class Address
+
+ include TextUtils
+
+ def Address.parse( str )
+ Parser.parse :ADDRESS, str
+ end
+
+ def address_group?
+ false
+ end
+
+ def initialize( local, domain )
+ if domain
+ domain.each do |s|
+ raise SyntaxError, 'empty word in domain' if s.empty?
+ end
+ end
+ @local = local
+ @domain = domain
+ @name = nil
+ @routes = []
+ end
+
+ attr_reader :name
+
+ def name=( str )
+ @name = str
+ @name = nil if str and str.empty?
+ end
+
+ alias phrase name
+ alias phrase= name=
+
+ attr_reader :routes
+
+ def inspect
+ "#<#{self.class} #{address()}>"
+ end
+
+ def local
+ return nil unless @local
+ return '""' if @local.size == 1 and @local[0].empty?
+ @local.map {|i| quote_atom(i) }.join('.')
+ end
+
+ def domain
+ return nil unless @domain
+ join_domain(@domain)
+ end
+
+ def spec
+ s = self.local
+ d = self.domain
+ if s and d
+ s + '@' + d
+ else
+ s
+ end
+ end
+
+ alias address spec
+
+
+ def ==( other )
+ other.respond_to? :spec and self.spec == other.spec
+ end
+
+ alias eql? ==
+
+ def hash
+ @local.hash ^ @domain.hash
+ end
+
+ def dup
+ obj = self.class.new(@local.dup, @domain.dup)
+ obj.name = @name.dup if @name
+ obj.routes.replace @routes
+ obj
+ end
+
+ include StrategyInterface
+
+ def accept( strategy, dummy1 = nil, dummy2 = nil )
+ unless @local
+ strategy.meta '<>' # empty return-path
+ return
+ end
+
+ spec_p = (not @name and @routes.empty?)
+ if @name
+ strategy.phrase @name
+ strategy.space
+ end
+ tmp = spec_p ? '' : '<'
+ unless @routes.empty?
+ tmp << @routes.map {|i| '@' + i }.join(',') << ':'
+ end
+ tmp << self.spec
+ tmp << '>' unless spec_p
+ strategy.meta tmp
+ strategy.lwsp ''
+ end
+
+ end
+
+
+ class AddressGroup
+
+ include Enumerable
+
+ def address_group?
+ true
+ end
+
+ def initialize( name, addrs )
+ @name = name
+ @addresses = addrs
+ end
+
+ attr_reader :name
+
+ def ==( other )
+ other.respond_to? :to_a and @addresses == other.to_a
+ end
+
+ alias eql? ==
+
+ def hash
+ map {|i| i.hash }.hash
+ end
+
+ def []( idx )
+ @addresses[idx]
+ end
+
+ def size
+ @addresses.size
+ end
+
+ def empty?
+ @addresses.empty?
+ end
+
+ def each( &block )
+ @addresses.each(&block)
+ end
+
+ def to_a
+ @addresses.dup
+ end
+
+ alias to_ary to_a
+
+ def include?( a )
+ @addresses.include? a
+ end
+
+ def flatten
+ set = []
+ @addresses.each do |a|
+ if a.respond_to? :flatten
+ set.concat a.flatten
+ else
+ set.push a
+ end
+ end
+ set
+ end
+
+ def each_address( &block )
+ flatten.each(&block)
+ end
+
+ def add( a )
+ @addresses.push a
+ end
+
+ alias push add
+
+ def delete( a )
+ @addresses.delete a
+ end
+
+ include StrategyInterface
+
+ def accept( strategy, dummy1 = nil, dummy2 = nil )
+ strategy.phrase @name
+ strategy.meta ':'
+ strategy.space
+ first = true
+ each do |mbox|
+ if first
+ first = false
+ else
+ strategy.meta ','
+ end
+ strategy.space
+ mbox.accept strategy
+ end
+ strategy.meta ';'
+ strategy.lwsp ''
+ end
+
+ end
+
+end # module TMail
diff --git a/actionmailer/lib/action_mailer/vendor/tmail/base64.rb b/actionmailer/lib/action_mailer/vendor/tmail/base64.rb
new file mode 100755
index 0000000000..d08a4fca7e
--- /dev/null
+++ b/actionmailer/lib/action_mailer/vendor/tmail/base64.rb
@@ -0,0 +1,52 @@
+#
+# base64.rb
+#
+# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
+#
+# This program is free software.
+# You can distribute/modify this program under the terms of
+# the GNU Lesser General Public License version 2 or later.
+#
+
+module TMail
+
+ module Base64
+
+ module_function
+
+ def rb_folding_encode( str, eol = "\n", limit = 60 )
+ [str].pack('m')
+ end
+
+ def rb_encode( str )
+ [str].pack('m').tr( "\r\n", '' )
+ end
+
+ def rb_decode( str, strict = false )
+ str.unpack('m')
+ end
+
+ begin
+ require 'tmail/base64.so'
+ alias folding_encode c_folding_encode
+ alias encode c_encode
+ alias decode c_decode
+ class << self
+ alias folding_encode c_folding_encode
+ alias encode c_encode
+ alias decode c_decode
+ end
+ rescue LoadError
+ alias folding_encode rb_folding_encode
+ alias encode rb_encode
+ alias decode rb_decode
+ class << self
+ alias folding_encode rb_folding_encode
+ alias encode rb_encode
+ alias decode rb_decode
+ end
+ end
+
+ end
+
+end
diff --git a/actionmailer/lib/action_mailer/vendor/tmail/config.rb b/actionmailer/lib/action_mailer/vendor/tmail/config.rb
new file mode 100755
index 0000000000..c40e5fb384
--- /dev/null
+++ b/actionmailer/lib/action_mailer/vendor/tmail/config.rb
@@ -0,0 +1,50 @@
+#
+# config.rb
+#
+# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
+#
+# This program is free software.
+# You can distribute/modify this program under the terms of
+# the GNU Lesser General Public License version 2 or later.
+#
+
+module TMail
+
+ class Config
+
+ def initialize( strict )
+ @strict_parse = strict
+ @strict_base64decode = strict
+ end
+
+ def strict_parse?
+ @strict_parse
+ end
+
+ attr_writer :strict_parse
+
+ def strict_base64decode?
+ @strict_base64decode
+ end
+
+ attr_writer :strict_base64decode
+
+ def new_body_port( mail )
+ StringPort.new
+ end
+
+ alias new_preamble_port new_body_port
+ alias new_part_port new_body_port
+
+ end
+
+ DEFAULT_CONFIG = Config.new(false)
+ DEFAULT_STRICT_CONFIG = Config.new(true)
+
+ def Config.to_config( arg )
+ return DEFAULT_STRICT_CONFIG if arg == true
+ return DEFAULT_CONFIG if arg == false
+ arg or DEFAULT_CONFIG
+ end
+
+end
diff --git a/actionmailer/lib/action_mailer/vendor/tmail/encode.rb b/actionmailer/lib/action_mailer/vendor/tmail/encode.rb
new file mode 100755
index 0000000000..8f33386f4d
--- /dev/null
+++ b/actionmailer/lib/action_mailer/vendor/tmail/encode.rb
@@ -0,0 +1,447 @@
+#
+# encode.rb
+#
+# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
+#
+# This program is free software.
+# You can distribute/modify this program under the terms of
+# the GNU Lesser General Public License version 2 or later.
+#
+
+require 'nkf'
+require 'tmail/base64.rb'
+require 'tmail/stringio'
+require 'tmail/utils'
+
+
+module TMail
+
+ module StrategyInterface
+
+ def create_dest( obj )
+ case obj
+ when nil
+ StringOutput.new
+ when String
+ StringOutput.new(obj)
+ when IO, StringOutput
+ obj
+ else
+ raise TypeError, 'cannot handle this type of object for dest'
+ end
+ end
+ module_function :create_dest
+
+ def encoded( eol = "\r\n", charset = 'j', dest = nil )
+ accept_strategy Encoder, eol, charset, dest
+ end
+
+ def decoded( eol = "\n", charset = 'e', dest = nil )
+ accept_strategy Decoder, eol, charset, dest
+ end
+
+ alias to_s decoded
+
+ def accept_strategy( klass, eol, charset, dest = nil )
+ dest ||= ''
+ accept klass.new(create_dest(dest), charset, eol)
+ dest
+ end
+
+ end
+
+
+ ###
+ ### MIME B encoding decoder
+ ###
+
+ class Decoder
+
+ include TextUtils
+
+ encoded = '=\?(?:iso-2022-jp|euc-jp|shift_jis)\?[QB]\?[a-z0-9+/=]+\?='
+ ENCODED_WORDS = /#{encoded}(?:\s+#{encoded})*/i
+
+ OUTPUT_ENCODING = {
+ 'EUC' => 'e',
+ 'SJIS' => 's',
+ }
+
+ def self.decode( str, encoding = nil )
+ encoding ||= (OUTPUT_ENCODING[$KCODE] || 'j')
+ opt = '-m' + encoding
+ str.gsub(ENCODED_WORDS) {|s| NKF.nkf(opt, s) }
+ end
+
+ def initialize( dest, encoding = nil, eol = "\n" )
+ @f = StrategyInterface.create_dest(dest)
+ @encoding = (/\A[ejs]/ === encoding) ? encoding[0,1] : nil
+ @eol = eol
+ end
+
+ def decode( str )
+ self.class.decode(str, @encoding)
+ end
+ private :decode
+
+ def terminate
+ end
+
+ def header_line( str )
+ @f << decode(str)
+ end
+
+ def header_name( nm )
+ @f << nm << ': '
+ end
+
+ def header_body( str )
+ @f << decode(str)
+ end
+
+ def space
+ @f << ' '
+ end
+
+ alias spc space
+
+ def lwsp( str )
+ @f << str
+ end
+
+ def meta( str )
+ @f << str
+ end
+
+ def text( str )
+ @f << decode(str)
+ end
+
+ def phrase( str )
+ @f << quote_phrase(decode(str))
+ end
+
+ def kv_pair( k, v )
+ @f << k << '=' << v
+ end
+
+ def puts( str = nil )
+ @f << str if str
+ @f << @eol
+ end
+
+ def write( str )
+ @f << str
+ end
+
+ end
+
+
+ ###
+ ### MIME B-encoding encoder
+ ###
+
+ #
+ # FIXME: This class can handle only (euc-jp/shift_jis -> iso-2022-jp).
+ #
+ class Encoder
+
+ include TextUtils
+
+ BENCODE_DEBUG = false unless defined?(BENCODE_DEBUG)
+
+ def Encoder.encode( str )
+ e = new()
+ e.header_body str
+ e.terminate
+ e.dest.string
+ end
+
+ SPACER = "\t"
+ MAX_LINE_LEN = 70
+
+ OPTIONS = {
+ 'EUC' => '-Ej -m0',
+ 'SJIS' => '-Sj -m0',
+ 'UTF8' => nil, # FIXME
+ 'NONE' => nil
+ }
+
+ def initialize( dest = nil, encoding = nil, eol = "\r\n", limit = nil )
+ @f = StrategyInterface.create_dest(dest)
+ @opt = OPTIONS[$KCODE]
+ @eol = eol
+ reset
+ end
+
+ def normalize_encoding( str )
+ if @opt
+ then NKF.nkf(@opt, str)
+ else str
+ end
+ end
+
+ def reset
+ @text = ''
+ @lwsp = ''
+ @curlen = 0
+ end
+
+ def terminate
+ add_lwsp ''
+ reset
+ end
+
+ def dest
+ @f
+ end
+
+ def puts( str = nil )
+ @f << str if str
+ @f << @eol
+ end
+
+ def write( str )
+ @f << str
+ end
+
+ #
+ # add
+ #
+
+ def header_line( line )
+ scanadd line
+ end
+
+ def header_name( name )
+ add_text name.split(/-/).map {|i| i.capitalize }.join('-')
+ add_text ':'
+ add_lwsp ' '
+ end
+
+ def header_body( str )
+ scanadd normalize_encoding(str)
+ end
+
+ def space
+ add_lwsp ' '
+ end
+
+ alias spc space
+
+ def lwsp( str )
+ add_lwsp str.sub(/[\r\n]+[^\r\n]*\z/, '')
+ end
+
+ def meta( str )
+ add_text str
+ end
+
+ def text( str )
+ scanadd normalize_encoding(str)
+ end
+
+ def phrase( str )
+ str = normalize_encoding(str)
+ if CONTROL_CHAR === str
+ scanadd str
+ else
+ add_text quote_phrase(str)
+ end
+ end
+
+ # FIXME: implement line folding
+ #
+ def kv_pair( k, v )
+ v = normalize_encoding(v)
+ if token_safe?(v)
+ add_text k + '=' + v
+ elsif not CONTROL_CHAR === v
+ add_text k + '=' + quote_token(v)
+ else
+ # apply RFC2231 encoding
+ kv = k + '*=' + "iso-2022-jp'ja'" + encode_value(v)
+ add_text kv
+ end
+ end
+
+ def encode_value( str )
+ str.gsub(TOKEN_UNSAFE) {|s| '%%%02x' % s[0] }
+ end
+
+ private
+
+ def scanadd( str, force = false )
+ types = ''
+ strs = []
+
+ until str.empty?
+ if m = /\A[^\e\t\r\n ]+/.match(str)
+ types << (force ? 'j' : 'a')
+ strs.push m[0]
+
+ elsif m = /\A[\t\r\n ]+/.match(str)
+ types << 's'
+ strs.push m[0]
+
+ elsif m = /\A\e../.match(str)
+ esc = m[0]
+ str = m.post_match
+ if esc != "\e(B" and m = /\A[^\e]+/.match(str)
+ types << 'j'
+ strs.push m[0]
+ end
+
+ else
+ raise 'TMail FATAL: encoder scan fail'
+ end
+ str = m.post_match
+ end
+
+ do_encode types, strs
+ end
+
+ def do_encode( types, strs )
+ #
+ # result : (A|E)(S(A|E))*
+ # E : W(SW)*
+ # W : (J|A)+ but must contain J # (J|A)*J(J|A)*
+ # A : <<A character string not to be encoded>>
+ # J : <<A character string to be encoded>>
+ # S : <<LWSP>>
+ #
+ # An encoding unit is `E'.
+ # Input (parameter `types') is (J|A)(J|A|S)*(J|A)
+ #
+ if BENCODE_DEBUG
+ puts
+ puts '-- do_encode ------------'
+ puts types.split(//).join(' ')
+ p strs
+ end
+
+ e = /[ja]*j[ja]*(?:s[ja]*j[ja]*)*/
+
+ while m = e.match(types)
+ pre = m.pre_match
+ concat_A_S pre, strs[0, pre.size] unless pre.empty?
+ concat_E m[0], strs[m.begin(0) ... m.end(0)]
+ types = m.post_match
+ strs.slice! 0, m.end(0)
+ end
+ concat_A_S types, strs
+ end
+
+ def concat_A_S( types, strs )
+ i = 0
+ types.each_byte do |t|
+ case t
+ when ?a then add_text strs[i]
+ when ?s then add_lwsp strs[i]
+ else
+ raise "TMail FATAL: unknown flag: #{t.chr}"
+ end
+ i += 1
+ end
+ end
+
+ METHOD_ID = {
+ ?j => :extract_J,
+ ?e => :extract_E,
+ ?a => :extract_A,
+ ?s => :extract_S
+ }
+
+ def concat_E( types, strs )
+ if BENCODE_DEBUG
+ puts '---- concat_E'
+ puts "types=#{types.split(//).join(' ')}"
+ puts "strs =#{strs.inspect}"
+ end
+
+ flush() unless @text.empty?
+
+ chunk = ''
+ strs.each_with_index do |s,i|
+ mid = METHOD_ID[types[i]]
+ until s.empty?
+ unless c = __send__(mid, chunk.size, s)
+ add_with_encode chunk unless chunk.empty?
+ flush
+ chunk = ''
+ fold
+ c = __send__(mid, 0, s)
+ raise 'TMail FATAL: extract fail' unless c
+ end
+ chunk << c
+ end
+ end
+ add_with_encode chunk unless chunk.empty?
+ end
+
+ def extract_J( chunksize, str )
+ size = max_bytes(chunksize, str.size) - 6
+ size = (size % 2 == 0) ? (size) : (size - 1)
+ return nil if size <= 0
+ "\e$B#{str.slice!(0, size)}\e(B"
+ end
+
+ def extract_A( chunksize, str )
+ size = max_bytes(chunksize, str.size)
+ return nil if size <= 0
+ str.slice!(0, size)
+ end
+
+ alias extract_S extract_A
+
+ def max_bytes( chunksize, ssize )
+ (restsize() - '=?iso-2022-jp?B??='.size) / 4 * 3 - chunksize
+ end
+
+ #
+ # free length buffer
+ #
+
+ def add_text( str )
+ @text << str
+ # puts '---- text -------------------------------------'
+ # puts "+ #{str.inspect}"
+ # puts "txt >>>#{@text.inspect}<<<"
+ end
+
+ def add_with_encode( str )
+ @text << "=?iso-2022-jp?B?#{Base64.encode(str)}?="
+ end
+
+ def add_lwsp( lwsp )
+ # puts '---- lwsp -------------------------------------'
+ # puts "+ #{lwsp.inspect}"
+ fold if restsize() <= 0
+ flush
+ @lwsp = lwsp
+ end
+
+ def flush
+ # puts '---- flush ----'
+ # puts "spc >>>#{@lwsp.inspect}<<<"
+ # puts "txt >>>#{@text.inspect}<<<"
+ @f << @lwsp << @text
+ @curlen += (@lwsp.size + @text.size)
+ @text = ''
+ @lwsp = ''
+ end
+
+ def fold
+ # puts '---- fold ----'
+ @f << @eol
+ @curlen = 0
+ @lwsp = SPACER
+ end
+
+ def restsize
+ MAX_LINE_LEN - (@curlen + @lwsp.size + @text.size)
+ end
+
+ end
+
+end # module TMail
diff --git a/actionmailer/lib/action_mailer/vendor/tmail/facade.rb b/actionmailer/lib/action_mailer/vendor/tmail/facade.rb
new file mode 100755
index 0000000000..4b8e2fbc07
--- /dev/null
+++ b/actionmailer/lib/action_mailer/vendor/tmail/facade.rb
@@ -0,0 +1,531 @@
+#
+# facade.rb
+#
+# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
+#
+# This program is free software.
+# You can distribute/modify this program under the terms of
+# the GNU Lesser General Public License version 2 or later.
+#
+
+require 'tmail/utils'
+
+
+module TMail
+
+ class Mail
+
+ def header_string( name, default = nil )
+ h = @header[name.downcase] or return default
+ h.to_s
+ end
+
+ ###
+ ### attributes
+ ###
+
+ include TextUtils
+
+ def set_string_array_attr( key, strs )
+ strs.flatten!
+ if strs.empty?
+ @header.delete key.downcase
+ else
+ store key, strs.join(', ')
+ end
+ strs
+ end
+ private :set_string_array_attr
+
+ def set_string_attr( key, str )
+ if str
+ store key, str
+ else
+ @header.delete key.downcase
+ end
+ str
+ end
+ private :set_string_attr
+
+ def set_addrfield( name, arg )
+ if arg
+ h = HeaderField.internal_new(name, @config)
+ h.addrs.replace [arg].flatten
+ @header[name] = h
+ else
+ @header.delete name
+ end
+ arg
+ end
+ private :set_addrfield
+
+ def addrs2specs( addrs )
+ return nil unless addrs
+ list = addrs.map {|addr|
+ if addr.address_group?
+ then addr.map {|a| a.spec }
+ else addr.spec
+ end
+ }.flatten
+ return nil if list.empty?
+ list
+ end
+ private :addrs2specs
+
+
+ #
+ # date time
+ #
+
+ def date( default = nil )
+ if h = @header['date']
+ h.date
+ else
+ default
+ end
+ end
+
+ def date=( time )
+ if time
+ store 'Date', time2str(time)
+ else
+ @header.delete 'date'
+ end
+ time
+ end
+
+ def strftime( fmt, default = nil )
+ if t = date
+ t.strftime(fmt)
+ else
+ default
+ end
+ end
+
+
+ #
+ # destination
+ #
+
+ def to_addrs( default = nil )
+ if h = @header['to']
+ h.addrs
+ else
+ default
+ end
+ end
+
+ def cc_addrs( default = nil )
+ if h = @header['cc']
+ h.addrs
+ else
+ default
+ end
+ end
+
+ def bcc_addrs( default = nil )
+ if h = @header['bcc']
+ h.addrs
+ else
+ default
+ end
+ end
+
+ def to_addrs=( arg )
+ set_addrfield 'to', arg
+ end
+
+ def cc_addrs=( arg )
+ set_addrfield 'cc', arg
+ end
+
+ def bcc_addrs=( arg )
+ set_addrfield 'bcc', arg
+ end
+
+ def to( default = nil )
+ addrs2specs(to_addrs(nil)) || default
+ end
+
+ def cc( default = nil )
+ addrs2specs(cc_addrs(nil)) || default
+ end
+
+ def bcc( default = nil )
+ addrs2specs(bcc_addrs(nil)) || default
+ end
+
+ def to=( *strs )
+ set_string_array_attr 'To', strs
+ end
+
+ def cc=( *strs )
+ set_string_array_attr 'Cc', strs
+ end
+
+ def bcc=( *strs )
+ set_string_array_attr 'Bcc', strs
+ end
+
+
+ #
+ # originator
+ #
+
+ def from_addrs( default = nil )
+ if h = @header['from']
+ h.addrs
+ else
+ default
+ end
+ end
+
+ def from_addrs=( arg )
+ set_addrfield 'from', arg
+ end
+
+ def from( default = nil )
+ addrs2specs(from_addrs(nil)) || default
+ end
+
+ def from=( *strs )
+ set_string_array_attr 'From', strs
+ end
+
+ def friendly_from( default = nil )
+ h = @header['from']
+ a, = h.addrs
+ return default unless a
+ return a.phrase if a.phrase
+ return h.comments.join(' ') unless h.comments.empty?
+ a.spec
+ end
+
+
+ def reply_to_addrs( default = nil )
+ if h = @header['reply-to']
+ h.addrs
+ else
+ default
+ end
+ end
+
+ def reply_to_addrs=( arg )
+ set_addrfield 'reply-to', arg
+ end
+
+ def reply_to( default = nil )
+ addrs2specs(reply_to_addrs(nil)) || default
+ end
+
+ def reply_to=( *strs )
+ set_string_array_attr 'Reply-To', strs
+ end
+
+
+ def sender_addr( default = nil )
+ f = @header['sender'] or return default
+ f.addr or return default
+ end
+
+ def sender_addr=( addr )
+ if addr
+ h = HeaderField.internal_new('sender', @config)
+ h.addr = addr
+ @header['sender'] = h
+ else
+ @header.delete 'sender'
+ end
+ addr
+ end
+
+ def sender( default )
+ f = @header['sender'] or return default
+ a = f.addr or return default
+ a.spec
+ end
+
+ def sender=( str )
+ set_string_attr 'Sender', str
+ end
+
+
+ #
+ # subject
+ #
+
+ def subject( default = nil )
+ if h = @header['subject']
+ h.body
+ else
+ default
+ end
+ end
+
+ def subject=( str )
+ set_string_attr 'Subject', str
+ end
+
+
+ #
+ # identity & threading
+ #
+
+ def message_id( default = nil )
+ if h = @header['message-id']
+ h.id || default
+ else
+ default
+ end
+ end
+
+ def message_id=( str )
+ set_string_attr 'Message-Id', str
+ end
+
+ def in_reply_to( default = nil )
+ if h = @header['in-reply-to']
+ h.ids
+ else
+ default
+ end
+ end
+
+ def in_reply_to=( *idstrs )
+ set_string_array_attr 'In-Reply-To', idstrs
+ end
+
+ def references( default = nil )
+ if h = @header['references']
+ h.refs
+ else
+ default
+ end
+ end
+
+ def references=( *strs )
+ set_string_array_attr 'References', strs
+ end
+
+
+ #
+ # MIME headers
+ #
+
+ def mime_version( default = nil )
+ if h = @header['mime-version']
+ h.version || default
+ else
+ default
+ end
+ end
+
+ def mime_version=( m, opt = nil )
+ if opt
+ if h = @header['mime-version']
+ h.major = m
+ h.minor = opt
+ else
+ store 'Mime-Version', "#{m}.#{opt}"
+ end
+ else
+ store 'Mime-Version', m
+ end
+ m
+ end
+
+
+ def content_type( default = nil )
+ if h = @header['content-type']
+ h.content_type || default
+ else
+ default
+ end
+ end
+
+ def main_type( default = nil )
+ if h = @header['content-type']
+ h.main_type || default
+ else
+ default
+ end
+ end
+
+ def sub_type( default = nil )
+ if h = @header['content-type']
+ h.sub_type || default
+ else
+ default
+ end
+ end
+
+ def set_content_type( str, sub = nil, param = nil )
+ if sub
+ main, sub = str, sub
+ else
+ main, sub = str.split(%r</>, 2)
+ raise ArgumentError, "sub type missing: #{str.inspect}" unless sub
+ end
+ if h = @header['content-type']
+ h.main_type = main
+ h.sub_type = sub
+ h.params.clear
+ else
+ store 'Content-Type', "#{main}/#{sub}"
+ end
+ @header['content-type'].params.replace param if param
+
+ str
+ end
+
+ alias content_type= set_content_type
+
+ def type_param( name, default = nil )
+ if h = @header['content-type']
+ h[name] || default
+ else
+ default
+ end
+ end
+
+ def charset( default = nil )
+ if h = @header['content-type']
+ h['charset'] or default
+ else
+ default
+ end
+ end
+
+ def charset=( str )
+ if str
+ if h = @header[ 'content-type' ]
+ h['charset'] = str
+ else
+ store 'Content-Type', "text/plain; charset=#{str}"
+ end
+ end
+ str
+ end
+
+
+ def transfer_encoding( default = nil )
+ if h = @header['content-transfer-encoding']
+ h.encoding || default
+ else
+ default
+ end
+ end
+
+ def transfer_encoding=( str )
+ set_string_attr 'Content-Transfer-Encoding', str
+ end
+
+ alias encoding transfer_encoding
+ alias encoding= transfer_encoding=
+ alias content_transfer_encoding transfer_encoding
+ alias content_transfer_encoding= transfer_encoding=
+
+
+ def disposition( default = nil )
+ if h = @header['content-disposition']
+ h.disposition || default
+ else
+ default
+ end
+ end
+
+ alias content_disposition disposition
+
+ def set_disposition( str, params = nil )
+ if h = @header['content-disposition']
+ h.disposition = str
+ h.params.clear
+ else
+ h = store('Content-Disposition', str)
+ end
+ h.params.replace params if params
+ end
+
+ alias disposition= set_disposition
+ alias set_content_disposition set_disposition
+ alias content_disposition= set_disposition
+
+ def disposition_param( name, default = nil )
+ if h = @header['content-disposition']
+ h[name] || default
+ else
+ default
+ end
+ end
+
+ ###
+ ### utils
+ ###
+
+ def create_reply
+ mail = TMail::Mail.parse('')
+ mail.subject = 'Re: ' + subject('').sub(/\A(?:\[[^\]]+\])?(?:\s*Re:)*\s*/i, '')
+ mail.to_addrs = reply_addresses([])
+ mail.in_reply_to = [message_id(nil)].compact
+ mail.references = references([]) + [message_id(nil)].compact
+ mail.mime_version = '1.0'
+ mail
+ end
+
+
+ def base64_encode
+ store 'Content-Transfer-Encoding', 'Base64'
+ self.body = Base64.folding_encode(self.body)
+ end
+
+ def base64_decode
+ if /base64/i === self.transfer_encoding('')
+ store 'Content-Transfer-Encoding', '8bit'
+ self.body = Base64.decode(self.body, @config.strict_base64decode?)
+ end
+ end
+
+
+ def destinations( default = nil )
+ ret = []
+ %w( to cc bcc ).each do |nm|
+ if h = @header[nm]
+ h.addrs.each {|i| ret.push i.address }
+ end
+ end
+ ret.empty? ? default : ret
+ end
+
+ def each_destination( &block )
+ destinations([]).each do |i|
+ if Address === i
+ yield i
+ else
+ i.each(&block)
+ end
+ end
+ end
+
+ alias each_dest each_destination
+
+
+ def reply_addresses( default = nil )
+ reply_to_addrs(nil) or from_addrs(nil) or default
+ end
+
+ def error_reply_addresses( default = nil )
+ if s = sender(nil)
+ [s]
+ else
+ from_addrs(default)
+ end
+ end
+
+
+ def multipart?
+ main_type('').downcase == 'multipart'
+ end
+
+ end # class Mail
+
+end # module TMail
diff --git a/actionmailer/lib/action_mailer/vendor/tmail/header.rb b/actionmailer/lib/action_mailer/vendor/tmail/header.rb
new file mode 100755
index 0000000000..73639b5629
--- /dev/null
+++ b/actionmailer/lib/action_mailer/vendor/tmail/header.rb
@@ -0,0 +1,893 @@
+#
+# header.rb
+#
+# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
+#
+# This program is free software.
+# You can distribute/modify this program under the terms of
+# the GNU Lesser General Public License version 2 or later.
+#
+
+require 'tmail/encode'
+require 'tmail/address'
+require 'tmail/parser'
+require 'tmail/config'
+require 'tmail/utils'
+
+
+module TMail
+
+ class HeaderField
+
+ include TextUtils
+
+ class << self
+
+ alias newobj new
+
+ def new( name, body, conf = DEFAULT_CONFIG )
+ klass = FNAME_TO_CLASS[name.downcase] || UnstructuredHeader
+ klass.newobj body, conf
+ end
+
+ def new_from_port( port, name, conf = DEFAULT_CONFIG )
+ re = Regep.new('\A(' + Regexp.quote(name) + '):', 'i')
+ str = nil
+ port.ropen {|f|
+ f.each do |line|
+ if m = re.match(line) then str = m.post_match.strip
+ elsif str and /\A[\t ]/ === line then str << ' ' << line.strip
+ elsif /\A-*\s*\z/ === line then break
+ elsif str then break
+ end
+ end
+ }
+ new(name, str, Config.to_config(conf))
+ end
+
+ def internal_new( name, conf )
+ FNAME_TO_CLASS[name].newobj('', conf, true)
+ end
+
+ end # class << self
+
+ def initialize( body, conf, intern = false )
+ @body = body
+ @config = conf
+
+ @illegal = false
+ @parsed = false
+ if intern
+ @parsed = true
+ parse_init
+ end
+ end
+
+ def inspect
+ "#<#{self.class} #{@body.inspect}>"
+ end
+
+ def illegal?
+ @illegal
+ end
+
+ def empty?
+ ensure_parsed
+ return true if @illegal
+ isempty?
+ end
+
+ private
+
+ def ensure_parsed
+ return if @parsed
+ @parsed = true
+ parse
+ end
+
+ # defabstract parse
+ # end
+
+ def clear_parse_status
+ @parsed = false
+ @illegal = false
+ end
+
+ public
+
+ def body
+ ensure_parsed
+ v = Decoder.new(s = '')
+ do_accept v
+ v.terminate
+ s
+ end
+
+ def body=( str )
+ @body = str
+ clear_parse_status
+ end
+
+ include StrategyInterface
+
+ def accept( strategy, dummy1 = nil, dummy2 = nil )
+ ensure_parsed
+ do_accept strategy
+ strategy.terminate
+ end
+
+ # abstract do_accept
+
+ end
+
+
+ class UnstructuredHeader < HeaderField
+
+ def body
+ ensure_parsed
+ @body
+ end
+
+ def body=( arg )
+ ensure_parsed
+ @body = arg
+ end
+
+ private
+
+ def parse_init
+ end
+
+ def parse
+ @body = Decoder.decode(@body.gsub(/\n|\r\n|\r/, ''))
+ end
+
+ def isempty?
+ not @body
+ end
+
+ def do_accept( strategy )
+ strategy.text @body
+ end
+
+ end
+
+
+ class StructuredHeader < HeaderField
+
+ def comments
+ ensure_parsed
+ @comments
+ end
+
+ private
+
+ def parse
+ save = nil
+
+ begin
+ parse_init
+ do_parse
+ rescue SyntaxError
+ if not save and mime_encoded? @body
+ save = @body
+ @body = Decoder.decode(save)
+ retry
+ elsif save
+ @body = save
+ end
+
+ @illegal = true
+ raise if @config.strict_parse?
+ end
+ end
+
+ def parse_init
+ @comments = []
+ init
+ end
+
+ def do_parse
+ obj = Parser.parse(self.class::PARSE_TYPE, @body, @comments)
+ set obj if obj
+ end
+
+ end
+
+
+ class DateTimeHeader < StructuredHeader
+
+ PARSE_TYPE = :DATETIME
+
+ def date
+ ensure_parsed
+ @date
+ end
+
+ def date=( arg )
+ ensure_parsed
+ @date = arg
+ end
+
+ private
+
+ def init
+ @date = nil
+ end
+
+ def set( t )
+ @date = t
+ end
+
+ def isempty?
+ not @date
+ end
+
+ def do_accept( strategy )
+ strategy.meta time2str(@date)
+ end
+
+ end
+
+
+ class AddressHeader < StructuredHeader
+
+ PARSE_TYPE = :MADDRESS
+
+ def addrs
+ ensure_parsed
+ @addrs
+ end
+
+ private
+
+ def init
+ @addrs = []
+ end
+
+ def set( a )
+ @addrs = a
+ end
+
+ def isempty?
+ @addrs.empty?
+ end
+
+ def do_accept( strategy )
+ first = true
+ @addrs.each do |a|
+ if first
+ first = false
+ else
+ strategy.meta ','
+ strategy.space
+ end
+ a.accept strategy
+ end
+
+ @comments.each do |c|
+ strategy.space
+ strategy.meta '('
+ strategy.text c
+ strategy.meta ')'
+ end
+ end
+
+ end
+
+
+ class ReturnPathHeader < AddressHeader
+
+ PARSE_TYPE = :RETPATH
+
+ def addr
+ addrs()[0]
+ end
+
+ def spec
+ a = addr() or return nil
+ a.spec
+ end
+
+ def routes
+ a = addr() or return nil
+ a.routes
+ end
+
+ private
+
+ def do_accept( strategy )
+ a = addr()
+
+ strategy.meta '<'
+ unless a.routes.empty?
+ strategy.meta a.routes.map {|i| '@' + i }.join(',')
+ strategy.meta ':'
+ end
+ spec = a.spec
+ strategy.meta spec if spec
+ strategy.meta '>'
+ end
+
+ end
+
+
+ class SingleAddressHeader < AddressHeader
+
+ def addr
+ addrs()[0]
+ end
+
+ private
+
+ def do_accept( strategy )
+ a = addr()
+ a.accept strategy
+ @comments.each do |c|
+ strategy.space
+ strategy.meta '('
+ strategy.text c
+ strategy.meta ')'
+ end
+ end
+
+ end
+
+
+ class MessageIdHeader < StructuredHeader
+
+ def id
+ ensure_parsed
+ @id
+ end
+
+ def id=( arg )
+ ensure_parsed
+ @id = arg
+ end
+
+ private
+
+ def init
+ @id = nil
+ end
+
+ def isempty?
+ not @id
+ end
+
+ def do_parse
+ @id = @body.slice(MESSAGE_ID) or
+ raise SyntaxError, "wrong Message-ID format: #{@body}"
+ end
+
+ def do_accept( strategy )
+ strategy.meta @id
+ end
+
+ end
+
+
+ class ReferencesHeader < StructuredHeader
+
+ def refs
+ ensure_parsed
+ @refs
+ end
+
+ def each_id
+ self.refs.each do |i|
+ yield i if MESSAGE_ID === i
+ end
+ end
+
+ def ids
+ ensure_parsed
+ @ids
+ end
+
+ def each_phrase
+ self.refs.each do |i|
+ yield i unless MESSAGE_ID === i
+ end
+ end
+
+ def phrases
+ ret = []
+ each_phrase {|i| ret.push i }
+ ret
+ end
+
+ private
+
+ def init
+ @refs = []
+ @ids = []
+ end
+
+ def isempty?
+ @ids.empty?
+ end
+
+ def do_parse
+ str = @body
+ while m = MESSAGE_ID.match(str)
+ pre = m.pre_match.strip
+ @refs.push pre unless pre.empty?
+ @refs.push s = m[0]
+ @ids.push s
+ str = m.post_match
+ end
+ str = str.strip
+ @refs.push str unless str.empty?
+ end
+
+ def do_accept( strategy )
+ first = true
+ @ids.each do |i|
+ if first
+ first = false
+ else
+ strategy.space
+ end
+ strategy.meta i
+ end
+ end
+
+ end
+
+
+ class ReceivedHeader < StructuredHeader
+
+ PARSE_TYPE = :RECEIVED
+
+ def from
+ ensure_parsed
+ @from
+ end
+
+ def from=( arg )
+ ensure_parsed
+ @from = arg
+ end
+
+ def by
+ ensure_parsed
+ @by
+ end
+
+ def by=( arg )
+ ensure_parsed
+ @by = arg
+ end
+
+ def via
+ ensure_parsed
+ @via
+ end
+
+ def via=( arg )
+ ensure_parsed
+ @via = arg
+ end
+
+ def with
+ ensure_parsed
+ @with
+ end
+
+ def id
+ ensure_parsed
+ @id
+ end
+
+ def id=( arg )
+ ensure_parsed
+ @id = arg
+ end
+
+ def _for
+ ensure_parsed
+ @_for
+ end
+
+ def _for=( arg )
+ ensure_parsed
+ @_for = arg
+ end
+
+ def date
+ ensure_parsed
+ @date
+ end
+
+ def date=( arg )
+ ensure_parsed
+ @date = arg
+ end
+
+ private
+
+ def init
+ @from = @by = @via = @with = @id = @_for = nil
+ @with = []
+ @date = nil
+ end
+
+ def set( args )
+ @from, @by, @via, @with, @id, @_for, @date = *args
+ end
+
+ def isempty?
+ @with.empty? and not (@from or @by or @via or @id or @_for or @date)
+ end
+
+ def do_accept( strategy )
+ list = []
+ list.push 'from ' + @from if @from
+ list.push 'by ' + @by if @by
+ list.push 'via ' + @via if @via
+ @with.each do |i|
+ list.push 'with ' + i
+ end
+ list.push 'id ' + @id if @id
+ list.push 'for <' + @_for + '>' if @_for
+
+ first = true
+ list.each do |i|
+ strategy.space unless first
+ strategy.meta i
+ first = false
+ end
+ if @date
+ strategy.meta ';'
+ strategy.space
+ strategy.meta time2str(@date)
+ end
+ end
+
+ end
+
+
+ class KeywordsHeader < StructuredHeader
+
+ PARSE_TYPE = :KEYWORDS
+
+ def keys
+ ensure_parsed
+ @keys
+ end
+
+ private
+
+ def init
+ @keys = []
+ end
+
+ def set( a )
+ @keys = a
+ end
+
+ def isempty?
+ @keys.empty?
+ end
+
+ def do_accept( strategy )
+ first = true
+ @keys.each do |i|
+ if first
+ first = false
+ else
+ strategy.meta ','
+ end
+ strategy.meta i
+ end
+ end
+
+ end
+
+
+ class EncryptedHeader < StructuredHeader
+
+ PARSE_TYPE = :ENCRYPTED
+
+ def encrypter
+ ensure_parsed
+ @encrypter
+ end
+
+ def encrypter=( arg )
+ ensure_parsed
+ @encrypter = arg
+ end
+
+ def keyword
+ ensure_parsed
+ @keyword
+ end
+
+ def keyword=( arg )
+ ensure_parsed
+ @keyword = arg
+ end
+
+ private
+
+ def init
+ @encrypter = nil
+ @keyword = nil
+ end
+
+ def set( args )
+ @encrypter, @keyword = args
+ end
+
+ def isempty?
+ not (@encrypter or @keyword)
+ end
+
+ def do_accept( strategy )
+ if @key
+ strategy.meta @encrypter + ','
+ strategy.space
+ strategy.meta @keyword
+ else
+ strategy.meta @encrypter
+ end
+ end
+
+ end
+
+
+ class MimeVersionHeader < StructuredHeader
+
+ PARSE_TYPE = :MIMEVERSION
+
+ def major
+ ensure_parsed
+ @major
+ end
+
+ def major=( arg )
+ ensure_parsed
+ @major = arg
+ end
+
+ def minor
+ ensure_parsed
+ @minor
+ end
+
+ def minor=( arg )
+ ensure_parsed
+ @minor = arg
+ end
+
+ def version
+ sprintf('%d.%d', major, minor)
+ end
+
+ private
+
+ def init
+ @major = nil
+ @minor = nil
+ end
+
+ def set( args )
+ @major, @minor = *args
+ end
+
+ def isempty?
+ not (@major or @minor)
+ end
+
+ def do_accept( strategy )
+ strategy.meta sprintf('%d.%d', @major, @minor)
+ end
+
+ end
+
+
+ class ContentTypeHeader < StructuredHeader
+
+ PARSE_TYPE = :CTYPE
+
+ def main_type
+ ensure_parsed
+ @main
+ end
+
+ def main_type=( arg )
+ ensure_parsed
+ @main = arg.downcase
+ end
+
+ def sub_type
+ ensure_parsed
+ @sub
+ end
+
+ def sub_type=( arg )
+ ensure_parsed
+ @sub = arg.downcase
+ end
+
+ def content_type
+ ensure_parsed
+ @sub ? sprintf('%s/%s', @main, @sub) : @main
+ end
+
+ def params
+ ensure_parsed
+ @params
+ end
+
+ def []( key )
+ ensure_parsed
+ @params and @params[key]
+ end
+
+ def []=( key, val )
+ ensure_parsed
+ (@params ||= {})[key] = val
+ end
+
+ private
+
+ def init
+ @main = @sub = @params = nil
+ end
+
+ def set( args )
+ @main, @sub, @params = *args
+ end
+
+ def isempty?
+ not (@main or @sub)
+ end
+
+ def do_accept( strategy )
+ if @sub
+ strategy.meta sprintf('%s/%s', @main, @sub)
+ else
+ strategy.meta @main
+ end
+ @params.each do |k,v|
+ strategy.meta ';'
+ strategy.space
+ strategy.kv_pair k, v
+ end
+ end
+
+ end
+
+
+ class ContentTransferEncodingHeader < StructuredHeader
+
+ PARSE_TYPE = :CENCODING
+
+ def encoding
+ ensure_parsed
+ @encoding
+ end
+
+ def encoding=( arg )
+ ensure_parsed
+ @encoding = arg
+ end
+
+ private
+
+ def init
+ @encoding = nil
+ end
+
+ def set( s )
+ @encoding = s
+ end
+
+ def isempty?
+ not @encoding
+ end
+
+ def do_accept( strategy )
+ strategy.meta @encoding.capitalize
+ end
+
+ end
+
+
+ class ContentDispositionHeader < StructuredHeader
+
+ PARSE_TYPE = :CDISPOSITION
+
+ def disposition
+ ensure_parsed
+ @disposition
+ end
+
+ def disposition=( str )
+ ensure_parsed
+ @disposition = str.downcase
+ end
+
+ def params
+ ensure_parsed
+ @params
+ end
+
+ def []( key )
+ ensure_parsed
+ @params and @params[key]
+ end
+
+ def []=( key, val )
+ ensure_parsed
+ (@params ||= {})[key] = val
+ end
+
+ private
+
+ def init
+ @disposition = @params = nil
+ end
+
+ def set( args )
+ @disposition, @params = *args
+ end
+
+ def isempty?
+ not @disposition and (not @params or @params.empty?)
+ end
+
+ def do_accept( strategy )
+ strategy.meta @disposition
+ @params.each do |k,v|
+ strategy.meta ';'
+ strategy.space
+ strategy.kv_pair k, v
+ end
+ end
+
+ end
+
+
+ class HeaderField # redefine
+
+ FNAME_TO_CLASS = {
+ 'date' => DateTimeHeader,
+ 'resent-date' => DateTimeHeader,
+ 'to' => AddressHeader,
+ 'cc' => AddressHeader,
+ 'bcc' => AddressHeader,
+ 'from' => AddressHeader,
+ 'reply-to' => AddressHeader,
+ 'resent-to' => AddressHeader,
+ 'resent-cc' => AddressHeader,
+ 'resent-bcc' => AddressHeader,
+ 'resent-from' => AddressHeader,
+ 'resent-reply-to' => AddressHeader,
+ 'sender' => SingleAddressHeader,
+ 'resent-sender' => SingleAddressHeader,
+ 'return-path' => ReturnPathHeader,
+ 'message-id' => MessageIdHeader,
+ 'resent-message-id' => MessageIdHeader,
+ 'in-reply-to' => ReferencesHeader,
+ 'received' => ReceivedHeader,
+ 'references' => ReferencesHeader,
+ 'keywords' => KeywordsHeader,
+ 'encrypted' => EncryptedHeader,
+ 'mime-version' => MimeVersionHeader,
+ 'content-type' => ContentTypeHeader,
+ 'content-transfer-encoding' => ContentTransferEncodingHeader,
+ 'content-disposition' => ContentDispositionHeader,
+ 'content-id' => MessageIdHeader,
+ 'subject' => UnstructuredHeader,
+ 'comments' => UnstructuredHeader,
+ 'content-description' => UnstructuredHeader
+ }
+
+ end
+
+end # module TMail
diff --git a/actionmailer/lib/action_mailer/vendor/tmail/info.rb b/actionmailer/lib/action_mailer/vendor/tmail/info.rb
new file mode 100755
index 0000000000..918f232096
--- /dev/null
+++ b/actionmailer/lib/action_mailer/vendor/tmail/info.rb
@@ -0,0 +1,16 @@
+#
+# info.rb
+#
+# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
+#
+# This program is free software.
+# You can distribute/modify this program under the terms of
+# the GNU Lesser General Public License version 2 or later.
+#
+
+module TMail
+
+ Version = '0.10.7'
+ Copyright = 'Copyright (c) 1998-2002 Minero Aoki'
+
+end
diff --git a/actionmailer/lib/action_mailer/vendor/tmail/loader.rb b/actionmailer/lib/action_mailer/vendor/tmail/loader.rb
new file mode 100755
index 0000000000..7907315401
--- /dev/null
+++ b/actionmailer/lib/action_mailer/vendor/tmail/loader.rb
@@ -0,0 +1 @@
+require 'tmail/mailbox'
diff --git a/actionmailer/lib/action_mailer/vendor/tmail/mail.rb b/actionmailer/lib/action_mailer/vendor/tmail/mail.rb
new file mode 100755
index 0000000000..bfea9b6db4
--- /dev/null
+++ b/actionmailer/lib/action_mailer/vendor/tmail/mail.rb
@@ -0,0 +1,420 @@
+#
+# mail.rb
+#
+# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
+#
+# This program is free software.
+# You can distribute/modify this program under the terms of
+# the GNU Lesser General Public License version 2 or later.
+#
+
+require 'tmail/facade'
+require 'tmail/encode'
+require 'tmail/header'
+require 'tmail/port'
+require 'tmail/config'
+require 'tmail/utils'
+require 'socket'
+
+
+module TMail
+
+ class Mail
+
+ class << self
+ def load( fname )
+ new(FilePort.new(fname))
+ end
+
+ alias load_from load
+ alias loadfrom load
+
+ def parse( str )
+ new(StringPort.new(str))
+ end
+ end
+
+ def initialize( port = nil, conf = DEFAULT_CONFIG )
+ @port = port || StringPort.new
+ @config = Config.to_config(conf)
+
+ @header = {}
+ @body_port = nil
+ @body_parsed = false
+ @epilogue = ''
+ @parts = []
+
+ @port.ropen {|f|
+ parse_header f
+ parse_body f unless @port.reproducible?
+ }
+ end
+
+ attr_reader :port
+
+ def inspect
+ "\#<#{self.class} port=#{@port.inspect} bodyport=#{@body_port.inspect}>"
+ end
+
+ #
+ # to_s interfaces
+ #
+
+ public
+
+ include StrategyInterface
+
+ def write_back( eol = "\n", charset = 'e' )
+ parse_body
+ @port.wopen {|stream| encoded eol, charset, stream }
+ end
+
+ def accept( strategy )
+ with_multipart_encoding(strategy) {
+ ordered_each do |name, field|
+ next if field.empty?
+ strategy.header_name canonical(name)
+ field.accept strategy
+ strategy.puts
+ end
+ strategy.puts
+ body_port().ropen {|r|
+ strategy.write r.read
+ }
+ }
+ end
+
+ private
+
+ def canonical( name )
+ name.split(/-/).map {|s| s.capitalize }.join('-')
+ end
+
+ def with_multipart_encoding( strategy )
+ if parts().empty? # DO NOT USE @parts
+ yield
+
+ else
+ bound = ::TMail.new_boundary
+ if @header.key? 'content-type'
+ @header['content-type'].params['boundary'] = bound
+ else
+ store 'Content-Type', %<multipart/mixed; boundary="#{bound}">
+ end
+
+ yield
+
+ parts().each do |tm|
+ strategy.puts
+ strategy.puts '--' + bound
+ tm.accept strategy
+ end
+ strategy.puts
+ strategy.puts '--' + bound + '--'
+ strategy.write epilogue()
+ end
+ end
+
+ ###
+ ### header
+ ###
+
+ public
+
+ ALLOW_MULTIPLE = {
+ 'received' => true,
+ 'resent-date' => true,
+ 'resent-from' => true,
+ 'resent-sender' => true,
+ 'resent-to' => true,
+ 'resent-cc' => true,
+ 'resent-bcc' => true,
+ 'resent-message-id' => true,
+ 'comments' => true,
+ 'keywords' => true
+ }
+ USE_ARRAY = ALLOW_MULTIPLE
+
+ def header
+ @header.dup
+ end
+
+ def []( key )
+ @header[key.downcase]
+ end
+
+ alias fetch []
+
+ def []=( key, val )
+ dkey = key.downcase
+
+ if val.nil?
+ @header.delete dkey
+ return nil
+ end
+
+ case val
+ when String
+ header = new_hf(key, val)
+ when HeaderField
+ ;
+ when Array
+ ALLOW_MULTIPLE.include? dkey or
+ raise ArgumentError, "#{key}: Header must not be multiple"
+ @header[dkey] = val
+ return val
+ else
+ header = new_hf(key, val.to_s)
+ end
+ if ALLOW_MULTIPLE.include? dkey
+ (@header[dkey] ||= []).push header
+ else
+ @header[dkey] = header
+ end
+
+ val
+ end
+
+ alias store []=
+
+ def each_header
+ @header.each do |key, val|
+ [val].flatten.each {|v| yield key, v }
+ end
+ end
+
+ alias each_pair each_header
+
+ def each_header_name( &block )
+ @header.each_key(&block)
+ end
+
+ alias each_key each_header_name
+
+ def each_field( &block )
+ @header.values.flatten.each(&block)
+ end
+
+ alias each_value each_field
+
+ FIELD_ORDER = %w(
+ return-path received
+ resent-date resent-from resent-sender resent-to
+ resent-cc resent-bcc resent-message-id
+ date from sender reply-to to cc bcc
+ message-id in-reply-to references
+ subject comments keywords
+ mime-version content-type content-transfer-encoding
+ content-disposition content-description
+ )
+
+ def ordered_each
+ list = @header.keys
+ FIELD_ORDER.each do |name|
+ if list.delete(name)
+ [@header[name]].flatten.each {|v| yield name, v }
+ end
+ end
+ list.each do |name|
+ [@header[name]].flatten.each {|v| yield name, v }
+ end
+ end
+
+ def clear
+ @header.clear
+ end
+
+ def delete( key )
+ @header.delete key.downcase
+ end
+
+ def delete_if
+ @header.delete_if do |key,val|
+ if Array === val
+ val.delete_if {|v| yield key, v }
+ val.empty?
+ else
+ yield key, val
+ end
+ end
+ end
+
+ def keys
+ @header.keys
+ end
+
+ def key?( key )
+ @header.key? key.downcase
+ end
+
+ def values_at( *args )
+ args.map {|k| @header[k.downcase] }.flatten
+ end
+
+ alias indexes values_at
+ alias indices values_at
+
+ private
+
+ def parse_header( f )
+ name = field = nil
+ unixfrom = nil
+
+ while line = f.gets
+ case line
+ when /\A[ \t]/ # continue from prev line
+ raise SyntaxError, 'mail is began by space' unless field
+ field << ' ' << line.strip
+
+ when /\A([^\: \t]+):\s*/ # new header line
+ add_hf name, field if field
+ name = $1
+ field = $' #.strip
+
+ when /\A\-*\s*\z/ # end of header
+ add_hf name, field if field
+ name = field = nil
+ break
+
+ when /\AFrom (\S+)/
+ unixfrom = $1
+
+ else
+ raise SyntaxError, "wrong mail header: '#{line.inspect}'"
+ end
+ end
+ add_hf name, field if name
+
+ if unixfrom
+ add_hf 'Return-Path', "<#{unixfrom}>" unless @header['return-path']
+ end
+ end
+
+ def add_hf( name, field )
+ key = name.downcase
+ field = new_hf(name, field)
+
+ if ALLOW_MULTIPLE.include? key
+ (@header[key] ||= []).push field
+ else
+ @header[key] = field
+ end
+ end
+
+ def new_hf( name, field )
+ HeaderField.new(name, field, @config)
+ end
+
+ ###
+ ### body
+ ###
+
+ public
+
+ def body_port
+ parse_body
+ @body_port
+ end
+
+ def each( &block )
+ body_port().ropen {|f| f.each(&block) }
+ end
+
+ def body
+ parse_body
+ @body_port.ropen {|f|
+ return f.read
+ }
+ end
+
+ def body=( str )
+ parse_body
+ @body_port.wopen {|f| f.write str }
+ str
+ end
+
+ alias preamble body
+ alias preamble= body=
+
+ def epilogue
+ parse_body
+ @epilogue.dup
+ end
+
+ def epilogue=( str )
+ parse_body
+ @epilogue = str
+ str
+ end
+
+ def parts
+ parse_body
+ @parts
+ end
+
+ def each_part( &block )
+ parts().each(&block)
+ end
+
+ private
+
+ def parse_body( f = nil )
+ return if @body_parsed
+ if f
+ parse_body_0 f
+ else
+ @port.ropen {|f|
+ skip_header f
+ parse_body_0 f
+ }
+ end
+ @body_parsed = true
+ end
+
+ def skip_header( f )
+ while line = f.gets
+ return if /\A[\r\n]*\z/ === line
+ end
+ end
+
+ def parse_body_0( f )
+ if multipart?
+ read_multipart f
+ else
+ @body_port = @config.new_body_port(self)
+ @body_port.wopen {|w|
+ w.write f.read
+ }
+ end
+ end
+
+ def read_multipart( src )
+ bound = @header['content-type'].params['boundary']
+ is_sep = /\A--#{Regexp.quote bound}(?:--)?[ \t]*(?:\n|\r\n|\r)/
+ lastbound = "--#{bound}--"
+
+ ports = [ @config.new_preamble_port(self) ]
+ begin
+ f = ports.last.wopen
+ while line = src.gets
+ if is_sep === line
+ f.close
+ break if line.strip == lastbound
+ ports.push @config.new_part_port(self)
+ f = ports.last.wopen
+ else
+ f << line
+ end
+ end
+ @epilogue = (src.read || '')
+ ensure
+ f.close if f and not f.closed?
+ end
+
+ @body_port = ports.shift
+ @parts = ports.map {|p| self.class.new(p, @config) }
+ end
+
+ end # class Mail
+
+end # module TMail
diff --git a/actionmailer/lib/action_mailer/vendor/tmail/mailbox.rb b/actionmailer/lib/action_mailer/vendor/tmail/mailbox.rb
new file mode 100755
index 0000000000..5c041c98a8
--- /dev/null
+++ b/actionmailer/lib/action_mailer/vendor/tmail/mailbox.rb
@@ -0,0 +1,414 @@
+#
+# mailbox.rb
+#
+# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
+#
+# This program is free software.
+# You can distribute/modify this program under the terms of
+# the GNU Lesser General Public License version 2 or later.
+#
+
+require 'tmail/port'
+require 'socket'
+require 'mutex_m'
+
+
+unless [].respond_to?(:sort_by)
+module Enumerable#:nodoc:
+ def sort_by
+ map {|i| [yield(i), i] }.sort {|a,b| a.first <=> b.first }.map {|i| i[1] }
+ end
+end
+end
+
+
+module TMail
+
+ class MhMailbox
+
+ PORT_CLASS = MhPort
+
+ def initialize( dir )
+ edir = File.expand_path(dir)
+ raise ArgumentError, "not directory: #{dir}"\
+ unless FileTest.directory? edir
+ @dirname = edir
+ @last_file = nil
+ @last_atime = nil
+ end
+
+ def directory
+ @dirname
+ end
+
+ alias dirname directory
+
+ attr_accessor :last_atime
+
+ def inspect
+ "#<#{self.class} #{@dirname}>"
+ end
+
+ def close
+ end
+
+ def new_port
+ PORT_CLASS.new(next_file_name())
+ end
+
+ def each_port
+ mail_files().each do |path|
+ yield PORT_CLASS.new(path)
+ end
+ @last_atime = Time.now
+ end
+
+ alias each each_port
+
+ def reverse_each_port
+ mail_files().reverse_each do |path|
+ yield PORT_CLASS.new(path)
+ end
+ @last_atime = Time.now
+ end
+
+ alias reverse_each reverse_each_port
+
+ # old #each_mail returns Port
+ #def each_mail
+ # each_port do |port|
+ # yield Mail.new(port)
+ # end
+ #end
+
+ def each_new_port( mtime = nil, &block )
+ mtime ||= @last_atime
+ return each_port(&block) unless mtime
+ return unless File.mtime(@dirname) >= mtime
+
+ mail_files().each do |path|
+ yield PORT_CLASS.new(path) if File.mtime(path) > mtime
+ end
+ @last_atime = Time.now
+ end
+
+ private
+
+ def mail_files
+ Dir.entries(@dirname)\
+ .select {|s| /\A\d+\z/ === s }\
+ .map {|s| s.to_i }\
+ .sort\
+ .map {|i| "#{@dirname}/#{i}" }\
+ .select {|path| FileTest.file? path }
+ end
+
+ def next_file_name
+ unless n = @last_file
+ n = 0
+ Dir.entries(@dirname)\
+ .select {|s| /\A\d+\z/ === s }\
+ .map {|s| s.to_i }.sort\
+ .each do |i|
+ next unless FileTest.file? "#{@dirname}/#{i}"
+ n = i
+ end
+ end
+ begin
+ n += 1
+ end while FileTest.exist? "#{@dirname}/#{n}"
+ @last_file = n
+
+ "#{@dirname}/#{n}"
+ end
+
+ end # MhMailbox
+
+ MhLoader = MhMailbox
+
+
+ class UNIXMbox
+
+ def UNIXMbox.lock( fname )
+ begin
+ f = File.open(fname)
+ f.flock File::LOCK_EX
+ yield f
+ ensure
+ f.flock File::LOCK_UN
+ f.close if f and not f.closed?
+ end
+ end
+
+ class << self
+ alias newobj new
+ end
+
+ def UNIXMbox.new( fname, tmpdir = nil, readonly = false )
+ tmpdir = ENV['TEMP'] || ENV['TMP'] || '/tmp'
+ newobj(fname, "#{tmpdir}/ruby_tmail_#{$$}_#{rand()}", readonly, false)
+ end
+
+ def UNIXMbox.static_new( fname, dir, readonly = false )
+ newobj(fname, dir, readonly, true)
+ end
+
+ def initialize( fname, mhdir, readonly, static )
+ @filename = fname
+ @readonly = readonly
+ @closed = false
+
+ Dir.mkdir mhdir
+ @real = MhMailbox.new(mhdir)
+ @finalizer = UNIXMbox.mkfinal(@real, @filename, !@readonly, !static)
+ ObjectSpace.define_finalizer self, @finalizer
+ end
+
+ def UNIXMbox.mkfinal( mh, mboxfile, writeback_p, cleanup_p )
+ lambda {
+ if writeback_p
+ lock(mboxfile) {|f|
+ mh.each_port do |port|
+ f.puts create_from_line(port)
+ port.ropen {|r|
+ f.puts r.read
+ }
+ end
+ }
+ end
+ if cleanup_p
+ Dir.foreach(mh.dirname) do |fname|
+ next if /\A\.\.?\z/ === fname
+ File.unlink "#{mh.dirname}/#{fname}"
+ end
+ Dir.rmdir mh.dirname
+ end
+ }
+ end
+
+ # make _From line
+ def UNIXMbox.create_from_line( port )
+ sprintf 'From %s %s',
+ fromaddr(), TextUtils.time2str(File.mtime(port.filename))
+ end
+
+ def UNIXMbox.fromaddr
+ h = HeaderField.new_from_port(port, 'Return-Path') ||
+ HeaderField.new_from_port(port, 'From') or return 'nobody'
+ a = h.addrs[0] or return 'nobody'
+ a.spec
+ end
+ private_class_method :fromaddr
+
+ def close
+ return if @closed
+
+ ObjectSpace.undefine_finalizer self
+ @finalizer.call
+ @finalizer = nil
+ @real = nil
+ @closed = true
+ @updated = nil
+ end
+
+ def each_port( &block )
+ close_check
+ update
+ @real.each_port(&block)
+ end
+
+ alias each each_port
+
+ def reverse_each_port( &block )
+ close_check
+ update
+ @real.reverse_each_port(&block)
+ end
+
+ alias reverse_each reverse_each_port
+
+ # old #each_mail returns Port
+ #def each_mail( &block )
+ # each_port do |port|
+ # yield Mail.new(port)
+ # end
+ #end
+
+ def each_new_port( mtime = nil )
+ close_check
+ update
+ @real.each_new_port(mtime) {|p| yield p }
+ end
+
+ def new_port
+ close_check
+ @real.new_port
+ end
+
+ private
+
+ def close_check
+ @closed and raise ArgumentError, 'accessing already closed mbox'
+ end
+
+ def update
+ return if FileTest.zero?(@filename)
+ return if @updated and File.mtime(@filename) < @updated
+ w = nil
+ port = nil
+ time = nil
+ UNIXMbox.lock(@filename) {|f|
+ begin
+ f.each do |line|
+ if /\AFrom / === line
+ w.close if w
+ File.utime time, time, port.filename if time
+
+ port = @real.new_port
+ w = port.wopen
+ time = fromline2time(line)
+ else
+ w.print line if w
+ end
+ end
+ ensure
+ if w and not w.closed?
+ w.close
+ File.utime time, time, port.filename if time
+ end
+ end
+ f.truncate(0) unless @readonly
+ @updated = Time.now
+ }
+ end
+
+ def fromline2time( line )
+ m = /\AFrom \S+ \w+ (\w+) (\d+) (\d+):(\d+):(\d+) (\d+)/.match(line) \
+ or return nil
+ Time.local(m[6].to_i, m[1], m[2].to_i, m[3].to_i, m[4].to_i, m[5].to_i)
+ end
+
+ end # UNIXMbox
+
+ MboxLoader = UNIXMbox
+
+
+ class Maildir
+
+ extend Mutex_m
+
+ PORT_CLASS = MaildirPort
+
+ @seq = 0
+ def Maildir.unique_number
+ synchronize {
+ @seq += 1
+ return @seq
+ }
+ end
+
+ def initialize( dir = nil )
+ @dirname = dir || ENV['MAILDIR']
+ raise ArgumentError, "not directory: #{@dirname}"\
+ unless FileTest.directory? @dirname
+ @new = "#{@dirname}/new"
+ @tmp = "#{@dirname}/tmp"
+ @cur = "#{@dirname}/cur"
+ end
+
+ def directory
+ @dirname
+ end
+
+ def inspect
+ "#<#{self.class} #{@dirname}>"
+ end
+
+ def close
+ end
+
+ def each_port
+ mail_files(@cur).each do |path|
+ yield PORT_CLASS.new(path)
+ end
+ end
+
+ alias each each_port
+
+ def reverse_each_port
+ mail_files(@cur).reverse_each do |path|
+ yield PORT_CLASS.new(path)
+ end
+ end
+
+ alias reverse_each reverse_each_port
+
+ def new_port
+ fname = nil
+ tmpfname = nil
+ newfname = nil
+
+ begin
+ fname = "#{Time.now.to_i}.#{$$}_#{Maildir.unique_number}.#{Socket.gethostname}"
+
+ tmpfname = "#{@tmp}/#{fname}"
+ newfname = "#{@new}/#{fname}"
+ end while FileTest.exist? tmpfname
+
+ if block_given?
+ File.open(tmpfname, 'w') {|f| yield f }
+ File.rename tmpfname, newfname
+ PORT_CLASS.new(newfname)
+ else
+ File.open(tmpfname, 'w') {|f| f.write "\n\n" }
+ PORT_CLASS.new(tmpfname)
+ end
+ end
+
+ def each_new_port
+ mail_files(@new).each do |path|
+ dest = @cur + '/' + File.basename(path)
+ File.rename path, dest
+ yield PORT_CLASS.new(dest)
+ end
+
+ check_tmp
+ end
+
+ TOO_OLD = 60 * 60 * 36 # 36 hour
+
+ def check_tmp
+ old = Time.now.to_i - TOO_OLD
+
+ each_filename(@tmp) do |full, fname|
+ if FileTest.file? full and
+ File.stat(full).mtime.to_i < old
+ File.unlink full
+ end
+ end
+ end
+
+ private
+
+ def mail_files( dir )
+ Dir.entries(dir)\
+ .select {|s| s[0] != ?. }\
+ .sort_by {|s| s.slice(/\A\d+/).to_i }\
+ .map {|s| "#{dir}/#{s}" }\
+ .select {|path| FileTest.file? path }
+ end
+
+ def each_filename( dir )
+ Dir.foreach(dir) do |fname|
+ path = "#{dir}/#{fname}"
+ if fname[0] != ?. and FileTest.file? path
+ yield path, fname
+ end
+ end
+ end
+
+ end # Maildir
+
+ MaildirLoader = Maildir
+
+end # module TMail
diff --git a/actionmailer/lib/action_mailer/vendor/tmail/mbox.rb b/actionmailer/lib/action_mailer/vendor/tmail/mbox.rb
new file mode 100755
index 0000000000..7907315401
--- /dev/null
+++ b/actionmailer/lib/action_mailer/vendor/tmail/mbox.rb
@@ -0,0 +1 @@
+require 'tmail/mailbox'
diff --git a/actionmailer/lib/action_mailer/vendor/tmail/net.rb b/actionmailer/lib/action_mailer/vendor/tmail/net.rb
new file mode 100755
index 0000000000..0ef433b88a
--- /dev/null
+++ b/actionmailer/lib/action_mailer/vendor/tmail/net.rb
@@ -0,0 +1,261 @@
+#
+# net.rb
+#
+# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
+#
+# This program is free software.
+# You can distribute/modify this program under the terms of
+# the GNU Lesser General Public License version 2 or later.
+#
+
+require 'nkf'
+
+
+module TMail
+
+ class Mail
+
+ def send_to( smtp )
+ do_send_to(smtp) do
+ ready_to_send
+ end
+ end
+
+ def send_text_to( smtp )
+ do_send_to(smtp) do
+ ready_to_send
+ mime_encode
+ end
+ end
+
+ def do_send_to( smtp )
+ from = from_address or raise ArgumentError, 'no from address'
+ (dests = destinations).empty? and raise ArgumentError, 'no receipient'
+ yield
+ send_to_0 smtp, from, dests
+ end
+ private :do_send_to
+
+ def send_to_0( smtp, from, to )
+ smtp.ready(from, to) do |f|
+ encoded "\r\n", 'j', f, ''
+ end
+ end
+
+ def ready_to_send
+ delete_no_send_fields
+ add_message_id
+ add_date
+ end
+
+ NOSEND_FIELDS = %w(
+ received
+ bcc
+ )
+
+ def delete_no_send_fields
+ NOSEND_FIELDS.each do |nm|
+ delete nm
+ end
+ delete_if {|n,v| v.empty? }
+ end
+
+ def add_message_id( fqdn = nil )
+ self.message_id = ::TMail::new_msgid(fqdn)
+ end
+
+ def add_date
+ self.date = Time.now
+ end
+
+ def mime_encode
+ if parts.empty?
+ mime_encode_singlepart
+ else
+ mime_encode_multipart true
+ end
+ end
+
+ def mime_encode_singlepart
+ self.mime_version = '1.0'
+ b = body
+ if NKF.guess(b) != NKF::BINARY
+ mime_encode_text b
+ else
+ mime_encode_binary b
+ end
+ end
+
+ def mime_encode_text( body )
+ self.body = NKF.nkf('-j -m0', body)
+ self.set_content_type 'text', 'plain', {'charset' => 'iso-2022-jp'}
+ self.encoding = '7bit'
+ end
+
+ def mime_encode_binary( body )
+ self.body = [body].pack('m')
+ self.set_content_type 'application', 'octet-stream'
+ self.encoding = 'Base64'
+ end
+
+ def mime_encode_multipart( top = true )
+ self.mime_version = '1.0' if top
+ self.set_content_type 'multipart', 'mixed'
+ e = encoding(nil)
+ if e and not /\A(?:7bit|8bit|binary)\z/i === e
+ raise ArgumentError,
+ 'using C.T.Encoding with multipart mail is not permitted'
+ end
+ end
+
+ def create_empty_mail
+ self.class.new(StringPort.new(''), @config)
+ end
+
+ def create_reply
+ setup_reply create_empty_mail()
+ end
+
+ def setup_reply( m )
+ if tmp = reply_addresses(nil)
+ m.to_addrs = tmp
+ end
+
+ mid = message_id(nil)
+ tmp = references(nil) || []
+ tmp.push mid if mid
+ m.in_reply_to = [mid] if mid
+ m.references = tmp unless tmp.empty?
+ m.subject = 'Re: ' + subject('').sub(/\A(?:\s*re:)+/i, '')
+
+ m
+ end
+
+ def create_forward
+ setup_forward create_empty_mail()
+ end
+
+ def setup_forward( mail )
+ m = Mail.new(StringPort.new(''))
+ m.body = decoded
+ m.set_content_type 'message', 'rfc822'
+ m.encoding = encoding('7bit')
+ mail.parts.push m
+ end
+
+ end
+
+
+ class DeleteFields
+
+ NOSEND_FIELDS = %w(
+ received
+ bcc
+ )
+
+ def initialize( nosend = nil, delempty = true )
+ @no_send_fields = nosend || NOSEND_FIELDS.dup
+ @delete_empty_fields = delempty
+ end
+
+ attr :no_send_fields
+ attr :delete_empty_fields, true
+
+ def exec( mail )
+ @no_send_fields.each do |nm|
+ delete nm
+ end
+ delete_if {|n,v| v.empty? } if @delete_empty_fields
+ end
+
+ end
+
+
+ class AddMessageId
+
+ def initialize( fqdn = nil )
+ @fqdn = fqdn
+ end
+
+ attr :fqdn, true
+
+ def exec( mail )
+ mail.message_id = ::TMail::new_msgid(@fqdn)
+ end
+
+ end
+
+
+ class AddDate
+
+ def exec( mail )
+ mail.date = Time.now
+ end
+
+ end
+
+
+ class MimeEncodeAuto
+
+ def initialize( s = nil, m = nil )
+ @singlepart_composer = s || MimeEncodeSingle.new
+ @multipart_composer = m || MimeEncodeMulti.new
+ end
+
+ attr :singlepart_composer
+ attr :multipart_composer
+
+ def exec( mail )
+ if mail._builtin_multipart?
+ then @multipart_composer
+ else @singlepart_composer end.exec mail
+ end
+
+ end
+
+
+ class MimeEncodeSingle
+
+ def exec( mail )
+ mail.mime_version = '1.0'
+ b = mail.body
+ if NKF.guess(b) != NKF::BINARY
+ on_text b
+ else
+ on_binary b
+ end
+ end
+
+ def on_text( body )
+ mail.body = NKF.nkf('-j -m0', body)
+ mail.set_content_type 'text', 'plain', {'charset' => 'iso-2022-jp'}
+ mail.encoding = '7bit'
+ end
+
+ def on_binary( body )
+ mail.body = [body].pack('m')
+ mail.set_content_type 'application', 'octet-stream'
+ mail.encoding = 'Base64'
+ end
+
+ end
+
+
+ class MimeEncodeMulti
+
+ def exec( mail, top = true )
+ mail.mime_version = '1.0' if top
+ mail.set_content_type 'multipart', 'mixed'
+ e = encoding(nil)
+ if e and not /\A(?:7bit|8bit|binary)\z/i === e
+ raise ArgumentError,
+ 'using C.T.Encoding with multipart mail is not permitted'
+ end
+ mail.parts.each do |m|
+ exec m, false if m._builtin_multipart?
+ end
+ end
+
+ end
+
+end # module TMail
diff --git a/actionmailer/lib/action_mailer/vendor/tmail/obsolete.rb b/actionmailer/lib/action_mailer/vendor/tmail/obsolete.rb
new file mode 100755
index 0000000000..1088453127
--- /dev/null
+++ b/actionmailer/lib/action_mailer/vendor/tmail/obsolete.rb
@@ -0,0 +1,116 @@
+#
+# obsolete.rb
+#
+# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
+#
+# This program is free software.
+# You can distribute/modify this program under the terms of
+# the GNU Lesser General Public License version 2 or later.
+#
+
+module TMail
+
+ # mail.rb
+ class Mail
+ alias include? key?
+ alias has_key? key?
+
+ def values
+ ret = []
+ each_field {|v| ret.push v }
+ ret
+ end
+
+ def value?( val )
+ HeaderField === val or return false
+
+ [ @header[val.name.downcase] ].flatten.include? val
+ end
+
+ alias has_value? value?
+ end
+
+
+ # facade.rb
+ class Mail
+ def from_addr( default = nil )
+ addr, = from_addrs(nil)
+ addr || default
+ end
+
+ def from_address( default = nil )
+ if a = from_addr(nil)
+ a.spec
+ else
+ default
+ end
+ end
+
+ alias from_address= from_addrs=
+
+ def from_phrase( default = nil )
+ if a = from_addr(nil)
+ a.phrase
+ else
+ default
+ end
+ end
+
+ alias msgid message_id
+ alias msgid= message_id=
+
+ alias each_dest each_destination
+ end
+
+
+ # address.rb
+ class Address
+ alias route routes
+ alias addr spec
+
+ def spec=( str )
+ @local, @domain = str.split(/@/,2).map {|s| s.split(/\./) }
+ end
+
+ alias addr= spec=
+ alias address= spec=
+ end
+
+
+ # mbox.rb
+ class MhMailbox
+ alias new_mail new_port
+ alias each_mail each_port
+ alias each_newmail each_new_port
+ end
+ class UNIXMbox
+ alias new_mail new_port
+ alias each_mail each_port
+ alias each_newmail each_new_port
+ end
+ class Maildir
+ alias new_mail new_port
+ alias each_mail each_port
+ alias each_newmail each_new_port
+ end
+
+
+ # utils.rb
+ extend TextUtils
+
+ class << self
+ alias msgid? message_id?
+ alias boundary new_boundary
+ alias msgid new_message_id
+ alias new_msgid new_message_id
+ end
+
+ def Mail.boundary
+ ::TMail.new_boundary
+ end
+
+ def Mail.msgid
+ ::TMail.new_message_id
+ end
+
+end # module TMail
diff --git a/actionmailer/lib/action_mailer/vendor/tmail/parser.rb b/actionmailer/lib/action_mailer/vendor/tmail/parser.rb
new file mode 100755
index 0000000000..c01b935891
--- /dev/null
+++ b/actionmailer/lib/action_mailer/vendor/tmail/parser.rb
@@ -0,0 +1,1503 @@
+#
+# DO NOT MODIFY!!!!
+# This file is automatically generated by racc 1.4.3
+# from racc grammer file "parser.y".
+#
+#
+# parser.rb: generated by racc (runtime embedded)
+#
+
+###### racc/parser.rb
+
+unless $".index 'racc/parser.rb'
+$".push 'racc/parser.rb'
+
+self.class.module_eval <<'..end /home/aamine/lib/ruby/racc/parser.rb modeval..idb76f2e220d', '/home/aamine/lib/ruby/racc/parser.rb', 1
+#
+# parser.rb
+#
+# Copyright (c) 1999-2003 Minero Aoki <aamine@loveruby.net>
+#
+# This program is free software.
+# You can distribute/modify this program under the same terms of ruby.
+#
+# As a special exception, when this code is copied by Racc
+# into a Racc output file, you may use that output file
+# without restriction.
+#
+# $Id: parser.rb,v 1.1.1.1 2004/10/14 11:59:58 webster132 Exp $
+#
+
+unless defined? NotImplementedError
+ NotImplementedError = NotImplementError
+end
+
+
+module Racc
+ class ParseError < StandardError; end
+end
+unless defined?(::ParseError)
+ ParseError = Racc::ParseError
+end
+
+
+module Racc
+
+ unless defined? Racc_No_Extentions
+ Racc_No_Extentions = false
+ end
+
+ class Parser
+
+ Racc_Runtime_Version = '1.4.3'
+ Racc_Runtime_Revision = '$Revision: 1.1.1.1 $'.split(/\s+/)[1]
+
+ Racc_Runtime_Core_Version_R = '1.4.3'
+ Racc_Runtime_Core_Revision_R = '$Revision: 1.1.1.1 $'.split(/\s+/)[1]
+ begin
+ require 'racc/cparse'
+ # Racc_Runtime_Core_Version_C = (defined in extention)
+ Racc_Runtime_Core_Revision_C = Racc_Runtime_Core_Id_C.split(/\s+/)[2]
+ unless new.respond_to?(:_racc_do_parse_c, true)
+ raise LoadError, 'old cparse.so'
+ end
+ if Racc_No_Extentions
+ raise LoadError, 'selecting ruby version of racc runtime core'
+ end
+
+ Racc_Main_Parsing_Routine = :_racc_do_parse_c
+ Racc_YY_Parse_Method = :_racc_yyparse_c
+ Racc_Runtime_Core_Version = Racc_Runtime_Core_Version_C
+ Racc_Runtime_Core_Revision = Racc_Runtime_Core_Revision_C
+ Racc_Runtime_Type = 'c'
+ rescue LoadError
+ Racc_Main_Parsing_Routine = :_racc_do_parse_rb
+ Racc_YY_Parse_Method = :_racc_yyparse_rb
+ Racc_Runtime_Core_Version = Racc_Runtime_Core_Version_R
+ Racc_Runtime_Core_Revision = Racc_Runtime_Core_Revision_R
+ Racc_Runtime_Type = 'ruby'
+ end
+
+ def self.racc_runtime_type
+ Racc_Runtime_Type
+ end
+
+ private
+
+ def _racc_setup
+ @yydebug = false unless self.class::Racc_debug_parser
+ @yydebug = false unless defined? @yydebug
+ if @yydebug
+ @racc_debug_out = $stderr unless defined? @racc_debug_out
+ @racc_debug_out ||= $stderr
+ end
+ arg = self.class::Racc_arg
+ arg[13] = true if arg.size < 14
+ arg
+ end
+
+ def _racc_init_sysvars
+ @racc_state = [0]
+ @racc_tstack = []
+ @racc_vstack = []
+
+ @racc_t = nil
+ @racc_val = nil
+
+ @racc_read_next = true
+
+ @racc_user_yyerror = false
+ @racc_error_status = 0
+ end
+
+
+ ###
+ ### do_parse
+ ###
+
+ def do_parse
+ __send__ Racc_Main_Parsing_Routine, _racc_setup(), false
+ end
+
+ def next_token
+ raise NotImplementedError, "#{self.class}\#next_token is not defined"
+ end
+
+ def _racc_do_parse_rb( arg, in_debug )
+ action_table, action_check, action_default, action_pointer,
+ goto_table, goto_check, goto_default, goto_pointer,
+ nt_base, reduce_table, token_table, shift_n,
+ reduce_n, use_result, * = arg
+
+ _racc_init_sysvars
+ tok = act = i = nil
+ nerr = 0
+
+ catch(:racc_end_parse) {
+ while true
+ if i = action_pointer[@racc_state[-1]]
+ if @racc_read_next
+ if @racc_t != 0 # not EOF
+ tok, @racc_val = next_token()
+ unless tok # EOF
+ @racc_t = 0
+ else
+ @racc_t = (token_table[tok] or 1) # error token
+ end
+ racc_read_token(@racc_t, tok, @racc_val) if @yydebug
+ @racc_read_next = false
+ end
+ end
+ i += @racc_t
+ if i >= 0 and
+ act = action_table[i] and
+ action_check[i] == @racc_state[-1]
+ ;
+ else
+ act = action_default[@racc_state[-1]]
+ end
+ else
+ act = action_default[@racc_state[-1]]
+ end
+ while act = _racc_evalact(act, arg)
+ end
+ end
+ }
+ end
+
+
+ ###
+ ### yyparse
+ ###
+
+ def yyparse( recv, mid )
+ __send__ Racc_YY_Parse_Method, recv, mid, _racc_setup(), true
+ end
+
+ def _racc_yyparse_rb( recv, mid, arg, c_debug )
+ action_table, action_check, action_default, action_pointer,
+ goto_table, goto_check, goto_default, goto_pointer,
+ nt_base, reduce_table, token_table, shift_n,
+ reduce_n, use_result, * = arg
+
+ _racc_init_sysvars
+ tok = nil
+ act = nil
+ i = nil
+ nerr = 0
+
+
+ catch(:racc_end_parse) {
+ until i = action_pointer[@racc_state[-1]]
+ while act = _racc_evalact(action_default[@racc_state[-1]], arg)
+ end
+ end
+
+ recv.__send__(mid) do |tok, val|
+# $stderr.puts "rd: tok=#{tok}, val=#{val}"
+ unless tok
+ @racc_t = 0
+ else
+ @racc_t = (token_table[tok] or 1) # error token
+ end
+ @racc_val = val
+ @racc_read_next = false
+
+ i += @racc_t
+ if i >= 0 and
+ act = action_table[i] and
+ action_check[i] == @racc_state[-1]
+ ;
+# $stderr.puts "01: act=#{act}"
+ else
+ act = action_default[@racc_state[-1]]
+# $stderr.puts "02: act=#{act}"
+# $stderr.puts "curstate=#{@racc_state[-1]}"
+ end
+
+ while act = _racc_evalact(act, arg)
+ end
+
+ while not (i = action_pointer[@racc_state[-1]]) or
+ not @racc_read_next or
+ @racc_t == 0 # $
+ if i and i += @racc_t and
+ i >= 0 and
+ act = action_table[i] and
+ action_check[i] == @racc_state[-1]
+ ;
+# $stderr.puts "03: act=#{act}"
+ else
+# $stderr.puts "04: act=#{act}"
+ act = action_default[@racc_state[-1]]
+ end
+
+ while act = _racc_evalact(act, arg)
+ end
+ end
+ end
+ }
+ end
+
+
+ ###
+ ### common
+ ###
+
+ def _racc_evalact( act, arg )
+# $stderr.puts "ea: act=#{act}"
+ action_table, action_check, action_default, action_pointer,
+ goto_table, goto_check, goto_default, goto_pointer,
+ nt_base, reduce_table, token_table, shift_n,
+ reduce_n, use_result, * = arg
+nerr = 0 # tmp
+
+ if act > 0 and act < shift_n
+ #
+ # shift
+ #
+
+ if @racc_error_status > 0
+ @racc_error_status -= 1 unless @racc_t == 1 # error token
+ end
+
+ @racc_vstack.push @racc_val
+ @racc_state.push act
+ @racc_read_next = true
+
+ if @yydebug
+ @racc_tstack.push @racc_t
+ racc_shift @racc_t, @racc_tstack, @racc_vstack
+ end
+
+ elsif act < 0 and act > -reduce_n
+ #
+ # reduce
+ #
+
+ code = catch(:racc_jump) {
+ @racc_state.push _racc_do_reduce(arg, act)
+ false
+ }
+ if code
+ case code
+ when 1 # yyerror
+ @racc_user_yyerror = true # user_yyerror
+ return -reduce_n
+ when 2 # yyaccept
+ return shift_n
+ else
+ raise RuntimeError, '[Racc Bug] unknown jump code'
+ end
+ end
+
+ elsif act == shift_n
+ #
+ # accept
+ #
+
+ racc_accept if @yydebug
+ throw :racc_end_parse, @racc_vstack[0]
+
+ elsif act == -reduce_n
+ #
+ # error
+ #
+
+ case @racc_error_status
+ when 0
+ unless arg[21] # user_yyerror
+ nerr += 1
+ on_error @racc_t, @racc_val, @racc_vstack
+ end
+ when 3
+ if @racc_t == 0 # is $
+ throw :racc_end_parse, nil
+ end
+ @racc_read_next = true
+ end
+ @racc_user_yyerror = false
+ @racc_error_status = 3
+
+ while true
+ if i = action_pointer[@racc_state[-1]]
+ i += 1 # error token
+ if i >= 0 and
+ (act = action_table[i]) and
+ action_check[i] == @racc_state[-1]
+ break
+ end
+ end
+
+ throw :racc_end_parse, nil if @racc_state.size < 2
+ @racc_state.pop
+ @racc_vstack.pop
+ if @yydebug
+ @racc_tstack.pop
+ racc_e_pop @racc_state, @racc_tstack, @racc_vstack
+ end
+ end
+
+ return act
+
+ else
+ raise RuntimeError, "[Racc Bug] unknown action #{act.inspect}"
+ end
+
+ racc_next_state(@racc_state[-1], @racc_state) if @yydebug
+
+ nil
+ end
+
+ def _racc_do_reduce( arg, act )
+ action_table, action_check, action_default, action_pointer,
+ goto_table, goto_check, goto_default, goto_pointer,
+ nt_base, reduce_table, token_table, shift_n,
+ reduce_n, use_result, * = arg
+ state = @racc_state
+ vstack = @racc_vstack
+ tstack = @racc_tstack
+
+ i = act * -3
+ len = reduce_table[i]
+ reduce_to = reduce_table[i+1]
+ method_id = reduce_table[i+2]
+ void_array = []
+
+ tmp_t = tstack[-len, len] if @yydebug
+ tmp_v = vstack[-len, len]
+ tstack[-len, len] = void_array if @yydebug
+ vstack[-len, len] = void_array
+ state[-len, len] = void_array
+
+ # tstack must be updated AFTER method call
+ if use_result
+ vstack.push __send__(method_id, tmp_v, vstack, tmp_v[0])
+ else
+ vstack.push __send__(method_id, tmp_v, vstack)
+ end
+ tstack.push reduce_to
+
+ racc_reduce(tmp_t, reduce_to, tstack, vstack) if @yydebug
+
+ k1 = reduce_to - nt_base
+ if i = goto_pointer[k1]
+ i += state[-1]
+ if i >= 0 and (curstate = goto_table[i]) and goto_check[i] == k1
+ return curstate
+ end
+ end
+ goto_default[k1]
+ end
+
+ def on_error( t, val, vstack )
+ raise ParseError, sprintf("\nparse error on value %s (%s)",
+ val.inspect, token_to_str(t) || '?')
+ end
+
+ def yyerror
+ throw :racc_jump, 1
+ end
+
+ def yyaccept
+ throw :racc_jump, 2
+ end
+
+ def yyerrok
+ @racc_error_status = 0
+ end
+
+
+ # for debugging output
+
+ def racc_read_token( t, tok, val )
+ @racc_debug_out.print 'read '
+ @racc_debug_out.print tok.inspect, '(', racc_token2str(t), ') '
+ @racc_debug_out.puts val.inspect
+ @racc_debug_out.puts
+ end
+
+ def racc_shift( tok, tstack, vstack )
+ @racc_debug_out.puts "shift #{racc_token2str tok}"
+ racc_print_stacks tstack, vstack
+ @racc_debug_out.puts
+ end
+
+ def racc_reduce( toks, sim, tstack, vstack )
+ out = @racc_debug_out
+ out.print 'reduce '
+ if toks.empty?
+ out.print ' <none>'
+ else
+ toks.each {|t| out.print ' ', racc_token2str(t) }
+ end
+ out.puts " --> #{racc_token2str(sim)}"
+
+ racc_print_stacks tstack, vstack
+ @racc_debug_out.puts
+ end
+
+ def racc_accept
+ @racc_debug_out.puts 'accept'
+ @racc_debug_out.puts
+ end
+
+ def racc_e_pop( state, tstack, vstack )
+ @racc_debug_out.puts 'error recovering mode: pop token'
+ racc_print_states state
+ racc_print_stacks tstack, vstack
+ @racc_debug_out.puts
+ end
+
+ def racc_next_state( curstate, state )
+ @racc_debug_out.puts "goto #{curstate}"
+ racc_print_states state
+ @racc_debug_out.puts
+ end
+
+ def racc_print_stacks( t, v )
+ out = @racc_debug_out
+ out.print ' ['
+ t.each_index do |i|
+ out.print ' (', racc_token2str(t[i]), ' ', v[i].inspect, ')'
+ end
+ out.puts ' ]'
+ end
+
+ def racc_print_states( s )
+ out = @racc_debug_out
+ out.print ' ['
+ s.each {|st| out.print ' ', st }
+ out.puts ' ]'
+ end
+
+ def racc_token2str( tok )
+ self.class::Racc_token_to_s_table[tok] or
+ raise RuntimeError, "[Racc Bug] can't convert token #{tok} to string"
+ end
+
+ def token_to_str( t )
+ self.class::Racc_token_to_s_table[t]
+ end
+
+ end
+
+end
+..end /home/aamine/lib/ruby/racc/parser.rb modeval..idb76f2e220d
+end # end of racc/parser.rb
+
+
+#
+# parser.rb
+#
+# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
+#
+# This program is free software.
+# You can distribute/modify this program under the terms of
+# the GNU Lesser General Public License version 2 or later.
+#
+
+require 'tmail/scanner'
+require 'tmail/utils'
+
+
+module TMail
+
+ class Parser < Racc::Parser
+
+module_eval <<'..end parser.y modeval..id43721faf1c', 'parser.y', 331
+
+ include TextUtils
+
+ def self.parse( ident, str, cmt = nil )
+ new.parse(ident, str, cmt)
+ end
+
+ MAILP_DEBUG = false
+
+ def initialize
+ self.debug = MAILP_DEBUG
+ end
+
+ def debug=( flag )
+ @yydebug = flag && Racc_debug_parser
+ @scanner_debug = flag
+ end
+
+ def debug
+ @yydebug
+ end
+
+ def parse( ident, str, comments = nil )
+ @scanner = Scanner.new(str, ident, comments)
+ @scanner.debug = @scanner_debug
+ @first = [ident, ident]
+ result = yyparse(self, :parse_in)
+ comments.map! {|c| to_kcode(c) } if comments
+ result
+ end
+
+ private
+
+ def parse_in( &block )
+ yield @first
+ @scanner.scan(&block)
+ end
+
+ def on_error( t, val, vstack )
+ raise SyntaxError, "parse error on token #{racc_token2str t}"
+ end
+
+..end parser.y modeval..id43721faf1c
+
+##### racc 1.4.3 generates ###
+
+racc_reduce_table = [
+ 0, 0, :racc_error,
+ 2, 35, :_reduce_1,
+ 2, 35, :_reduce_2,
+ 2, 35, :_reduce_3,
+ 2, 35, :_reduce_4,
+ 2, 35, :_reduce_5,
+ 2, 35, :_reduce_6,
+ 2, 35, :_reduce_7,
+ 2, 35, :_reduce_8,
+ 2, 35, :_reduce_9,
+ 2, 35, :_reduce_10,
+ 2, 35, :_reduce_11,
+ 2, 35, :_reduce_12,
+ 6, 36, :_reduce_13,
+ 0, 48, :_reduce_none,
+ 2, 48, :_reduce_none,
+ 3, 49, :_reduce_16,
+ 5, 49, :_reduce_17,
+ 1, 50, :_reduce_18,
+ 7, 37, :_reduce_19,
+ 0, 51, :_reduce_none,
+ 2, 51, :_reduce_21,
+ 0, 52, :_reduce_none,
+ 2, 52, :_reduce_23,
+ 1, 58, :_reduce_24,
+ 3, 58, :_reduce_25,
+ 2, 58, :_reduce_26,
+ 0, 53, :_reduce_none,
+ 2, 53, :_reduce_28,
+ 0, 54, :_reduce_29,
+ 3, 54, :_reduce_30,
+ 0, 55, :_reduce_none,
+ 2, 55, :_reduce_32,
+ 2, 55, :_reduce_33,
+ 0, 56, :_reduce_none,
+ 2, 56, :_reduce_35,
+ 1, 61, :_reduce_36,
+ 1, 61, :_reduce_37,
+ 0, 57, :_reduce_none,
+ 2, 57, :_reduce_39,
+ 1, 38, :_reduce_none,
+ 1, 38, :_reduce_none,
+ 3, 38, :_reduce_none,
+ 1, 46, :_reduce_none,
+ 1, 46, :_reduce_none,
+ 1, 46, :_reduce_none,
+ 1, 39, :_reduce_none,
+ 2, 39, :_reduce_47,
+ 1, 64, :_reduce_48,
+ 3, 64, :_reduce_49,
+ 1, 68, :_reduce_none,
+ 1, 68, :_reduce_none,
+ 1, 69, :_reduce_52,
+ 3, 69, :_reduce_53,
+ 1, 47, :_reduce_none,
+ 1, 47, :_reduce_none,
+ 2, 47, :_reduce_56,
+ 2, 67, :_reduce_none,
+ 3, 65, :_reduce_58,
+ 2, 65, :_reduce_59,
+ 1, 70, :_reduce_60,
+ 2, 70, :_reduce_61,
+ 4, 62, :_reduce_62,
+ 3, 62, :_reduce_63,
+ 2, 72, :_reduce_none,
+ 2, 73, :_reduce_65,
+ 4, 73, :_reduce_66,
+ 3, 63, :_reduce_67,
+ 1, 63, :_reduce_68,
+ 1, 74, :_reduce_none,
+ 2, 74, :_reduce_70,
+ 1, 71, :_reduce_71,
+ 3, 71, :_reduce_72,
+ 1, 59, :_reduce_73,
+ 3, 59, :_reduce_74,
+ 1, 76, :_reduce_75,
+ 2, 76, :_reduce_76,
+ 1, 75, :_reduce_none,
+ 1, 75, :_reduce_none,
+ 1, 75, :_reduce_none,
+ 1, 77, :_reduce_none,
+ 1, 77, :_reduce_none,
+ 1, 77, :_reduce_none,
+ 1, 66, :_reduce_none,
+ 2, 66, :_reduce_none,
+ 3, 60, :_reduce_85,
+ 1, 40, :_reduce_86,
+ 3, 40, :_reduce_87,
+ 1, 79, :_reduce_none,
+ 2, 79, :_reduce_89,
+ 1, 41, :_reduce_90,
+ 2, 41, :_reduce_91,
+ 3, 42, :_reduce_92,
+ 5, 43, :_reduce_93,
+ 3, 43, :_reduce_94,
+ 0, 80, :_reduce_95,
+ 5, 80, :_reduce_96,
+ 1, 82, :_reduce_none,
+ 1, 82, :_reduce_none,
+ 1, 44, :_reduce_99,
+ 3, 45, :_reduce_100,
+ 0, 81, :_reduce_none,
+ 1, 81, :_reduce_none,
+ 1, 78, :_reduce_none,
+ 1, 78, :_reduce_none,
+ 1, 78, :_reduce_none,
+ 1, 78, :_reduce_none,
+ 1, 78, :_reduce_none,
+ 1, 78, :_reduce_none,
+ 1, 78, :_reduce_none ]
+
+racc_reduce_n = 110
+
+racc_shift_n = 168
+
+racc_action_table = [
+ -70, -69, 23, 25, 146, 147, 29, 31, 105, 106,
+ 16, 17, 20, 22, 136, 27, -70, -69, 32, 101,
+ -70, -69, 154, 100, 113, 115, -70, -69, -70, 109,
+ 75, 23, 25, 101, 155, 29, 31, 142, 143, 16,
+ 17, 20, 22, 107, 27, 23, 25, 32, 98, 29,
+ 31, 96, 94, 16, 17, 20, 22, 78, 27, 23,
+ 25, 32, 112, 29, 31, 74, 91, 16, 17, 20,
+ 22, 88, 117, 92, 81, 32, 23, 25, 80, 123,
+ 29, 31, 100, 125, 16, 17, 20, 22, 126, 23,
+ 25, 109, 32, 29, 31, 91, 128, 16, 17, 20,
+ 22, 129, 27, 23, 25, 32, 101, 29, 31, 101,
+ 130, 16, 17, 20, 22, 79, 52, 23, 25, 32,
+ 78, 29, 31, 133, 78, 16, 17, 20, 22, 77,
+ 23, 25, 75, 32, 29, 31, 65, 62, 16, 17,
+ 20, 22, 139, 23, 25, 101, 32, 29, 31, 60,
+ 100, 16, 17, 20, 22, 44, 27, 101, 148, 32,
+ 23, 25, 120, 149, 29, 31, 152, 153, 16, 17,
+ 20, 22, 42, 27, 157, 159, 32, 23, 25, 120,
+ 40, 29, 31, 15, 164, 16, 17, 20, 22, 40,
+ 27, 23, 25, 32, 68, 29, 31, 166, 167, 16,
+ 17, 20, 22, nil, 27, 23, 25, 32, nil, 29,
+ 31, 74, nil, 16, 17, 20, 22, nil, 23, 25,
+ nil, 32, 29, 31, nil, nil, 16, 17, 20, 22,
+ nil, 23, 25, nil, 32, 29, 31, nil, nil, 16,
+ 17, 20, 22, nil, 23, 25, nil, 32, 29, 31,
+ nil, nil, 16, 17, 20, 22, nil, 23, 25, nil,
+ 32, 29, 31, nil, nil, 16, 17, 20, 22, nil,
+ 27, 23, 25, 32, nil, 29, 31, nil, nil, 16,
+ 17, 20, 22, nil, 23, 25, nil, 32, 29, 31,
+ nil, nil, 16, 17, 20, 22, nil, 23, 25, nil,
+ 32, 29, 31, nil, nil, 16, 17, 20, 22, nil,
+ 84, 25, nil, 32, 29, 31, nil, 87, 16, 17,
+ 20, 22, 4, 6, 7, 8, 9, 10, 11, 12,
+ 13, 1, 2, 3, 84, 25, nil, nil, 29, 31,
+ nil, 87, 16, 17, 20, 22, 84, 25, nil, nil,
+ 29, 31, nil, 87, 16, 17, 20, 22, 84, 25,
+ nil, nil, 29, 31, nil, 87, 16, 17, 20, 22,
+ 84, 25, nil, nil, 29, 31, nil, 87, 16, 17,
+ 20, 22, 84, 25, nil, nil, 29, 31, nil, 87,
+ 16, 17, 20, 22, 84, 25, nil, nil, 29, 31,
+ nil, 87, 16, 17, 20, 22 ]
+
+racc_action_check = [
+ 75, 28, 68, 68, 136, 136, 68, 68, 72, 72,
+ 68, 68, 68, 68, 126, 68, 75, 28, 68, 67,
+ 75, 28, 143, 66, 86, 86, 75, 28, 75, 75,
+ 28, 3, 3, 86, 143, 3, 3, 134, 134, 3,
+ 3, 3, 3, 73, 3, 152, 152, 3, 62, 152,
+ 152, 60, 56, 152, 152, 152, 152, 51, 152, 52,
+ 52, 152, 80, 52, 52, 52, 50, 52, 52, 52,
+ 52, 45, 89, 52, 42, 52, 71, 71, 41, 96,
+ 71, 71, 97, 98, 71, 71, 71, 71, 100, 7,
+ 7, 101, 71, 7, 7, 102, 104, 7, 7, 7,
+ 7, 105, 7, 8, 8, 7, 108, 8, 8, 111,
+ 112, 8, 8, 8, 8, 40, 8, 9, 9, 8,
+ 36, 9, 9, 117, 121, 9, 9, 9, 9, 33,
+ 10, 10, 70, 9, 10, 10, 13, 12, 10, 10,
+ 10, 10, 130, 2, 2, 131, 10, 2, 2, 11,
+ 135, 2, 2, 2, 2, 6, 2, 138, 139, 2,
+ 90, 90, 90, 140, 90, 90, 141, 142, 90, 90,
+ 90, 90, 5, 90, 148, 151, 90, 127, 127, 127,
+ 4, 127, 127, 1, 157, 127, 127, 127, 127, 159,
+ 127, 26, 26, 127, 26, 26, 26, 163, 164, 26,
+ 26, 26, 26, nil, 26, 27, 27, 26, nil, 27,
+ 27, 27, nil, 27, 27, 27, 27, nil, 155, 155,
+ nil, 27, 155, 155, nil, nil, 155, 155, 155, 155,
+ nil, 122, 122, nil, 155, 122, 122, nil, nil, 122,
+ 122, 122, 122, nil, 76, 76, nil, 122, 76, 76,
+ nil, nil, 76, 76, 76, 76, nil, 38, 38, nil,
+ 76, 38, 38, nil, nil, 38, 38, 38, 38, nil,
+ 38, 55, 55, 38, nil, 55, 55, nil, nil, 55,
+ 55, 55, 55, nil, 94, 94, nil, 55, 94, 94,
+ nil, nil, 94, 94, 94, 94, nil, 59, 59, nil,
+ 94, 59, 59, nil, nil, 59, 59, 59, 59, nil,
+ 114, 114, nil, 59, 114, 114, nil, 114, 114, 114,
+ 114, 114, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 77, 77, nil, nil, 77, 77,
+ nil, 77, 77, 77, 77, 77, 44, 44, nil, nil,
+ 44, 44, nil, 44, 44, 44, 44, 44, 113, 113,
+ nil, nil, 113, 113, nil, 113, 113, 113, 113, 113,
+ 88, 88, nil, nil, 88, 88, nil, 88, 88, 88,
+ 88, 88, 74, 74, nil, nil, 74, 74, nil, 74,
+ 74, 74, 74, 74, 129, 129, nil, nil, 129, 129,
+ nil, 129, 129, 129, 129, 129 ]
+
+racc_action_pointer = [
+ 320, 152, 129, 17, 165, 172, 137, 75, 89, 103,
+ 116, 135, 106, 105, nil, nil, nil, nil, nil, nil,
+ nil, nil, nil, nil, nil, nil, 177, 191, 1, nil,
+ nil, nil, nil, 109, nil, nil, 94, nil, 243, nil,
+ 99, 64, 74, nil, 332, 52, nil, nil, nil, nil,
+ 50, 31, 45, nil, nil, 257, 36, nil, nil, 283,
+ 22, nil, 16, nil, nil, nil, -3, -10, -12, nil,
+ 103, 62, -8, 15, 368, 0, 230, 320, nil, nil,
+ 47, nil, nil, nil, nil, nil, 4, nil, 356, 50,
+ 146, nil, nil, nil, 270, nil, 65, 56, 52, nil,
+ 57, 62, 79, nil, 68, 81, nil, nil, 77, nil,
+ nil, 80, 96, 344, 296, nil, nil, 108, nil, nil,
+ nil, 98, 217, nil, nil, nil, -19, 163, nil, 380,
+ 128, 116, nil, nil, 14, 124, -26, nil, 128, 141,
+ 148, 141, 152, 7, nil, nil, nil, nil, 160, nil,
+ nil, 149, 31, nil, nil, 204, nil, 167, nil, 174,
+ nil, nil, nil, 169, 184, nil, nil, nil ]
+
+racc_action_default = [
+ -110, -110, -110, -110, -14, -110, -20, -110, -110, -110,
+ -110, -110, -110, -110, -10, -95, -106, -107, -77, -44,
+ -108, -11, -109, -79, -43, -103, -110, -110, -60, -104,
+ -55, -105, -78, -68, -54, -71, -45, -12, -110, -1,
+ -110, -110, -110, -2, -110, -22, -51, -48, -50, -3,
+ -40, -41, -110, -46, -4, -86, -5, -88, -6, -90,
+ -110, -7, -95, -8, -9, -99, -101, -61, -59, -56,
+ -69, -110, -110, -110, -110, -75, -110, -110, -57, -15,
+ -110, 168, -73, -80, -82, -21, -24, -81, -110, -27,
+ -110, -83, -47, -89, -110, -91, -110, -101, -110, -100,
+ -102, -75, -58, -52, -110, -110, -64, -63, -65, -76,
+ -72, -67, -110, -110, -110, -26, -23, -110, -29, -49,
+ -84, -42, -87, -92, -94, -95, -110, -110, -62, -110,
+ -110, -25, -74, -28, -31, -101, -110, -53, -66, -110,
+ -110, -34, -110, -110, -93, -96, -98, -97, -110, -18,
+ -13, -38, -110, -30, -33, -110, -32, -16, -19, -14,
+ -35, -36, -37, -110, -110, -39, -85, -17 ]
+
+racc_goto_table = [
+ 39, 67, 70, 73, 24, 37, 69, 66, 36, 38,
+ 57, 59, 55, 67, 108, 83, 90, 111, 69, 99,
+ 85, 49, 53, 76, 158, 134, 141, 70, 73, 151,
+ 118, 89, 45, 156, 160, 150, 140, 21, 14, 19,
+ 119, 102, 64, 63, 61, 83, 70, 104, 83, 58,
+ 124, 132, 56, 131, 97, 54, 93, 43, 5, 83,
+ 95, 145, 76, nil, 116, 76, nil, nil, 127, 138,
+ 103, nil, nil, nil, 38, nil, nil, 110, nil, nil,
+ nil, nil, nil, nil, 83, 83, nil, nil, 144, nil,
+ nil, nil, nil, nil, nil, 57, 121, 122, nil, nil,
+ 83, nil, nil, nil, nil, nil, nil, nil, nil, nil,
+ nil, nil, nil, nil, nil, nil, nil, 135, nil, nil,
+ nil, nil, nil, 93, nil, nil, nil, 70, 162, 137,
+ 70, 163, 161, 38, nil, nil, nil, nil, nil, nil,
+ nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
+ nil, nil, nil, nil, nil, 165 ]
+
+racc_goto_check = [
+ 2, 37, 37, 29, 13, 13, 28, 46, 31, 36,
+ 41, 41, 45, 37, 25, 44, 32, 25, 28, 47,
+ 24, 4, 4, 42, 23, 20, 21, 37, 29, 22,
+ 19, 18, 17, 26, 27, 16, 15, 12, 11, 33,
+ 34, 35, 10, 9, 8, 44, 37, 29, 44, 7,
+ 47, 43, 6, 25, 46, 5, 41, 3, 1, 44,
+ 41, 48, 42, nil, 24, 42, nil, nil, 32, 25,
+ 13, nil, nil, nil, 36, nil, nil, 41, nil, nil,
+ nil, nil, nil, nil, 44, 44, nil, nil, 47, nil,
+ nil, nil, nil, nil, nil, 41, 31, 45, nil, nil,
+ 44, nil, nil, nil, nil, nil, nil, nil, nil, nil,
+ nil, nil, nil, nil, nil, nil, nil, 46, nil, nil,
+ nil, nil, nil, 41, nil, nil, nil, 37, 29, 13,
+ 37, 29, 28, 36, nil, nil, nil, nil, nil, nil,
+ nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
+ nil, nil, nil, nil, nil, 2 ]
+
+racc_goto_pointer = [
+ nil, 58, -4, 51, 14, 47, 43, 39, 33, 31,
+ 29, 37, 35, 2, nil, -94, -105, 26, -14, -59,
+ -93, -108, -112, -127, -24, -60, -110, -118, -20, -24,
+ nil, 6, -34, 37, -50, -27, 6, -25, nil, nil,
+ nil, 1, -5, -63, -29, 3, -8, -47, -75 ]
+
+racc_goto_default = [
+ nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
+ nil, nil, nil, 48, 41, nil, nil, nil, nil, nil,
+ nil, nil, nil, nil, nil, 86, nil, nil, 30, 34,
+ 50, 51, nil, 46, 47, nil, 26, 28, 71, 72,
+ 33, 35, 114, 82, 18, nil, nil, nil, nil ]
+
+racc_token_table = {
+ false => 0,
+ Object.new => 1,
+ :DATETIME => 2,
+ :RECEIVED => 3,
+ :MADDRESS => 4,
+ :RETPATH => 5,
+ :KEYWORDS => 6,
+ :ENCRYPTED => 7,
+ :MIMEVERSION => 8,
+ :CTYPE => 9,
+ :CENCODING => 10,
+ :CDISPOSITION => 11,
+ :ADDRESS => 12,
+ :MAILBOX => 13,
+ :DIGIT => 14,
+ :ATOM => 15,
+ "," => 16,
+ ":" => 17,
+ :FROM => 18,
+ :BY => 19,
+ "@" => 20,
+ :DOMLIT => 21,
+ :VIA => 22,
+ :WITH => 23,
+ :ID => 24,
+ :FOR => 25,
+ ";" => 26,
+ "<" => 27,
+ ">" => 28,
+ "." => 29,
+ :QUOTED => 30,
+ :TOKEN => 31,
+ "/" => 32,
+ "=" => 33 }
+
+racc_use_result_var = false
+
+racc_nt_base = 34
+
+Racc_arg = [
+ racc_action_table,
+ racc_action_check,
+ racc_action_default,
+ racc_action_pointer,
+ racc_goto_table,
+ racc_goto_check,
+ racc_goto_default,
+ racc_goto_pointer,
+ racc_nt_base,
+ racc_reduce_table,
+ racc_token_table,
+ racc_shift_n,
+ racc_reduce_n,
+ racc_use_result_var ]
+
+Racc_token_to_s_table = [
+'$end',
+'error',
+'DATETIME',
+'RECEIVED',
+'MADDRESS',
+'RETPATH',
+'KEYWORDS',
+'ENCRYPTED',
+'MIMEVERSION',
+'CTYPE',
+'CENCODING',
+'CDISPOSITION',
+'ADDRESS',
+'MAILBOX',
+'DIGIT',
+'ATOM',
+'","',
+'":"',
+'FROM',
+'BY',
+'"@"',
+'DOMLIT',
+'VIA',
+'WITH',
+'ID',
+'FOR',
+'";"',
+'"<"',
+'">"',
+'"."',
+'QUOTED',
+'TOKEN',
+'"/"',
+'"="',
+'$start',
+'content',
+'datetime',
+'received',
+'addrs_TOP',
+'retpath',
+'keys',
+'enc',
+'version',
+'ctype',
+'cencode',
+'cdisp',
+'addr_TOP',
+'mbox',
+'day',
+'hour',
+'zone',
+'from',
+'by',
+'via',
+'with',
+'id',
+'for',
+'received_datetime',
+'received_domain',
+'domain',
+'msgid',
+'received_addrspec',
+'routeaddr',
+'spec',
+'addrs',
+'group_bare',
+'commas',
+'group',
+'addr',
+'mboxes',
+'addr_phrase',
+'local_head',
+'routes',
+'at_domains',
+'local',
+'word',
+'dots',
+'domword',
+'atom',
+'phrase',
+'params',
+'opt_semicolon',
+'value']
+
+Racc_debug_parser = false
+
+##### racc system variables end #####
+
+ # reduce 0 omitted
+
+module_eval <<'.,.,', 'parser.y', 16
+ def _reduce_1( val, _values)
+ val[1]
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 17
+ def _reduce_2( val, _values)
+ val[1]
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 18
+ def _reduce_3( val, _values)
+ val[1]
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 19
+ def _reduce_4( val, _values)
+ val[1]
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 20
+ def _reduce_5( val, _values)
+ val[1]
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 21
+ def _reduce_6( val, _values)
+ val[1]
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 22
+ def _reduce_7( val, _values)
+ val[1]
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 23
+ def _reduce_8( val, _values)
+ val[1]
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 24
+ def _reduce_9( val, _values)
+ val[1]
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 25
+ def _reduce_10( val, _values)
+ val[1]
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 26
+ def _reduce_11( val, _values)
+ val[1]
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 27
+ def _reduce_12( val, _values)
+ val[1]
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 33
+ def _reduce_13( val, _values)
+ t = Time.gm(val[3].to_i, val[2], val[1].to_i, 0, 0, 0)
+ (t + val[4] - val[5]).localtime
+ end
+.,.,
+
+ # reduce 14 omitted
+
+ # reduce 15 omitted
+
+module_eval <<'.,.,', 'parser.y', 42
+ def _reduce_16( val, _values)
+ (val[0].to_i * 60 * 60) +
+ (val[2].to_i * 60)
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 47
+ def _reduce_17( val, _values)
+ (val[0].to_i * 60 * 60) +
+ (val[2].to_i * 60) +
+ (val[4].to_i)
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 54
+ def _reduce_18( val, _values)
+ timezone_string_to_unixtime(val[0])
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 59
+ def _reduce_19( val, _values)
+ val
+ end
+.,.,
+
+ # reduce 20 omitted
+
+module_eval <<'.,.,', 'parser.y', 65
+ def _reduce_21( val, _values)
+ val[1]
+ end
+.,.,
+
+ # reduce 22 omitted
+
+module_eval <<'.,.,', 'parser.y', 71
+ def _reduce_23( val, _values)
+ val[1]
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 77
+ def _reduce_24( val, _values)
+ join_domain(val[0])
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 81
+ def _reduce_25( val, _values)
+ join_domain(val[2])
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 85
+ def _reduce_26( val, _values)
+ join_domain(val[0])
+ end
+.,.,
+
+ # reduce 27 omitted
+
+module_eval <<'.,.,', 'parser.y', 91
+ def _reduce_28( val, _values)
+ val[1]
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 96
+ def _reduce_29( val, _values)
+ []
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 100
+ def _reduce_30( val, _values)
+ val[0].push val[2]
+ val[0]
+ end
+.,.,
+
+ # reduce 31 omitted
+
+module_eval <<'.,.,', 'parser.y', 107
+ def _reduce_32( val, _values)
+ val[1]
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 111
+ def _reduce_33( val, _values)
+ val[1]
+ end
+.,.,
+
+ # reduce 34 omitted
+
+module_eval <<'.,.,', 'parser.y', 117
+ def _reduce_35( val, _values)
+ val[1]
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 123
+ def _reduce_36( val, _values)
+ val[0].spec
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 127
+ def _reduce_37( val, _values)
+ val[0].spec
+ end
+.,.,
+
+ # reduce 38 omitted
+
+module_eval <<'.,.,', 'parser.y', 134
+ def _reduce_39( val, _values)
+ val[1]
+ end
+.,.,
+
+ # reduce 40 omitted
+
+ # reduce 41 omitted
+
+ # reduce 42 omitted
+
+ # reduce 43 omitted
+
+ # reduce 44 omitted
+
+ # reduce 45 omitted
+
+ # reduce 46 omitted
+
+module_eval <<'.,.,', 'parser.y', 146
+ def _reduce_47( val, _values)
+ [ Address.new(nil, nil) ]
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 148
+ def _reduce_48( val, _values)
+ val
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 149
+ def _reduce_49( val, _values)
+ val[0].push val[2]; val[0]
+ end
+.,.,
+
+ # reduce 50 omitted
+
+ # reduce 51 omitted
+
+module_eval <<'.,.,', 'parser.y', 156
+ def _reduce_52( val, _values)
+ val
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 160
+ def _reduce_53( val, _values)
+ val[0].push val[2]
+ val[0]
+ end
+.,.,
+
+ # reduce 54 omitted
+
+ # reduce 55 omitted
+
+module_eval <<'.,.,', 'parser.y', 168
+ def _reduce_56( val, _values)
+ val[1].phrase = Decoder.decode(val[0])
+ val[1]
+ end
+.,.,
+
+ # reduce 57 omitted
+
+module_eval <<'.,.,', 'parser.y', 176
+ def _reduce_58( val, _values)
+ AddressGroup.new(val[0], val[2])
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 178
+ def _reduce_59( val, _values)
+ AddressGroup.new(val[0], [])
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 181
+ def _reduce_60( val, _values)
+ val[0].join('.')
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 182
+ def _reduce_61( val, _values)
+ val[0] << ' ' << val[1].join('.')
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 186
+ def _reduce_62( val, _values)
+ val[2].routes.replace val[1]
+ val[2]
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 191
+ def _reduce_63( val, _values)
+ val[1]
+ end
+.,.,
+
+ # reduce 64 omitted
+
+module_eval <<'.,.,', 'parser.y', 196
+ def _reduce_65( val, _values)
+ [ val[1].join('.') ]
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 197
+ def _reduce_66( val, _values)
+ val[0].push val[3].join('.'); val[0]
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 199
+ def _reduce_67( val, _values)
+ Address.new( val[0], val[2] )
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 200
+ def _reduce_68( val, _values)
+ Address.new( val[0], nil )
+ end
+.,.,
+
+ # reduce 69 omitted
+
+module_eval <<'.,.,', 'parser.y', 203
+ def _reduce_70( val, _values)
+ val[0].push ''; val[0]
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 206
+ def _reduce_71( val, _values)
+ val
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 209
+ def _reduce_72( val, _values)
+ val[1].times do
+ val[0].push ''
+ end
+ val[0].push val[2]
+ val[0]
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 217
+ def _reduce_73( val, _values)
+ val
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 220
+ def _reduce_74( val, _values)
+ val[1].times do
+ val[0].push ''
+ end
+ val[0].push val[2]
+ val[0]
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 227
+ def _reduce_75( val, _values)
+ 0
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 228
+ def _reduce_76( val, _values)
+ 1
+ end
+.,.,
+
+ # reduce 77 omitted
+
+ # reduce 78 omitted
+
+ # reduce 79 omitted
+
+ # reduce 80 omitted
+
+ # reduce 81 omitted
+
+ # reduce 82 omitted
+
+ # reduce 83 omitted
+
+ # reduce 84 omitted
+
+module_eval <<'.,.,', 'parser.y', 243
+ def _reduce_85( val, _values)
+ val[1] = val[1].spec
+ val.join('')
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 247
+ def _reduce_86( val, _values)
+ val
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 248
+ def _reduce_87( val, _values)
+ val[0].push val[2]; val[0]
+ end
+.,.,
+
+ # reduce 88 omitted
+
+module_eval <<'.,.,', 'parser.y', 251
+ def _reduce_89( val, _values)
+ val[0] << ' ' << val[1]
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 255
+ def _reduce_90( val, _values)
+ val.push nil
+ val
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 260
+ def _reduce_91( val, _values)
+ val
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 265
+ def _reduce_92( val, _values)
+ [ val[0].to_i, val[2].to_i ]
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 270
+ def _reduce_93( val, _values)
+ [ val[0].downcase, val[2].downcase, decode_params(val[3]) ]
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 274
+ def _reduce_94( val, _values)
+ [ val[0].downcase, nil, decode_params(val[1]) ]
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 279
+ def _reduce_95( val, _values)
+ {}
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 283
+ def _reduce_96( val, _values)
+ val[0][ val[2].downcase ] = val[4]
+ val[0]
+ end
+.,.,
+
+ # reduce 97 omitted
+
+ # reduce 98 omitted
+
+module_eval <<'.,.,', 'parser.y', 292
+ def _reduce_99( val, _values)
+ val[0].downcase
+ end
+.,.,
+
+module_eval <<'.,.,', 'parser.y', 297
+ def _reduce_100( val, _values)
+ [ val[0].downcase, decode_params(val[1]) ]
+ end
+.,.,
+
+ # reduce 101 omitted
+
+ # reduce 102 omitted
+
+ # reduce 103 omitted
+
+ # reduce 104 omitted
+
+ # reduce 105 omitted
+
+ # reduce 106 omitted
+
+ # reduce 107 omitted
+
+ # reduce 108 omitted
+
+ # reduce 109 omitted
+
+ def _reduce_none( val, _values)
+ val[0]
+ end
+
+ end # class Parser
+
+end # module TMail
diff --git a/actionmailer/lib/action_mailer/vendor/tmail/port.rb b/actionmailer/lib/action_mailer/vendor/tmail/port.rb
new file mode 100755
index 0000000000..982aee8ba1
--- /dev/null
+++ b/actionmailer/lib/action_mailer/vendor/tmail/port.rb
@@ -0,0 +1,358 @@
+#
+# port.rb
+#
+# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
+#
+# This program is free software.
+# You can distribute/modify this program under the terms of
+# the GNU Lesser General Public License version 2 or later.
+#
+
+require 'tmail/stringio'
+
+
+module TMail
+
+ class Port
+ def reproducible?
+ false
+ end
+ end
+
+
+ ###
+ ### FilePort
+ ###
+
+ class FilePort < Port
+
+ def initialize( fname )
+ @filename = File.expand_path(fname)
+ super()
+ end
+
+ attr_reader :filename
+
+ alias ident filename
+
+ def ==( other )
+ other.respond_to?(:filename) and @filename == other.filename
+ end
+
+ alias eql? ==
+
+ def hash
+ @filename.hash
+ end
+
+ def inspect
+ "#<#{self.class}:#{@filename}>"
+ end
+
+ def reproducible?
+ true
+ end
+
+ def size
+ File.size @filename
+ end
+
+
+ def ropen( &block )
+ File.open(@filename, &block)
+ end
+
+ def wopen( &block )
+ File.open(@filename, 'w', &block)
+ end
+
+ def aopen( &block )
+ File.open(@filename, 'a', &block)
+ end
+
+
+ def read_all
+ ropen {|f|
+ return f.read
+ }
+ end
+
+
+ def remove
+ File.unlink @filename
+ end
+
+ def move_to( port )
+ begin
+ File.link @filename, port.filename
+ rescue Errno::EXDEV
+ copy_to port
+ end
+ File.unlink @filename
+ end
+
+ alias mv move_to
+
+ def copy_to( port )
+ if FilePort === port
+ copy_file @filename, port.filename
+ else
+ File.open(@filename) {|r|
+ port.wopen {|w|
+ while s = r.sysread(4096)
+ w.write << s
+ end
+ } }
+ end
+ end
+
+ alias cp copy_to
+
+ private
+
+ # from fileutils.rb
+ def copy_file( src, dest )
+ st = r = w = nil
+
+ File.open(src, 'rb') {|r|
+ File.open(dest, 'wb') {|w|
+ st = r.stat
+ begin
+ while true
+ w.write r.sysread(st.blksize)
+ end
+ rescue EOFError
+ end
+ } }
+ end
+
+ end
+
+
+ module MailFlags
+
+ def seen=( b )
+ set_status 'S', b
+ end
+
+ def seen?
+ get_status 'S'
+ end
+
+ def replied=( b )
+ set_status 'R', b
+ end
+
+ def replied?
+ get_status 'R'
+ end
+
+ def flagged=( b )
+ set_status 'F', b
+ end
+
+ def flagged?
+ get_status 'F'
+ end
+
+ private
+
+ def procinfostr( str, tag, true_p )
+ a = str.upcase.split(//)
+ a.push true_p ? tag : nil
+ a.delete tag unless true_p
+ a.compact.sort.join('').squeeze
+ end
+
+ end
+
+
+ class MhPort < FilePort
+
+ include MailFlags
+
+ private
+
+ def set_status( tag, flag )
+ begin
+ tmpfile = @filename + '.tmailtmp.' + $$.to_s
+ File.open(tmpfile, 'w') {|f|
+ write_status f, tag, flag
+ }
+ File.unlink @filename
+ File.link tmpfile, @filename
+ ensure
+ File.unlink tmpfile
+ end
+ end
+
+ def write_status( f, tag, flag )
+ stat = ''
+ File.open(@filename) {|r|
+ while line = r.gets
+ if line.strip.empty?
+ break
+ elsif m = /\AX-TMail-Status:/i.match(line)
+ stat = m.post_match.strip
+ else
+ f.print line
+ end
+ end
+
+ s = procinfostr(stat, tag, flag)
+ f.puts 'X-TMail-Status: ' + s unless s.empty?
+ f.puts
+
+ while s = r.read(2048)
+ f.write s
+ end
+ }
+ end
+
+ def get_status( tag )
+ File.foreach(@filename) {|line|
+ return false if line.strip.empty?
+ if m = /\AX-TMail-Status:/i.match(line)
+ return m.post_match.strip.include?(tag[0])
+ end
+ }
+ false
+ end
+
+ end
+
+
+ class MaildirPort < FilePort
+
+ def move_to_new
+ new = replace_dir(@filename, 'new')
+ File.rename @filename, new
+ @filename = new
+ end
+
+ def move_to_cur
+ new = replace_dir(@filename, 'cur')
+ File.rename @filename, new
+ @filename = new
+ end
+
+ def replace_dir( path, dir )
+ "#{File.dirname File.dirname(path)}/#{dir}/#{File.basename path}"
+ end
+ private :replace_dir
+
+
+ include MailFlags
+
+ private
+
+ MAIL_FILE = /\A(\d+\.[\d_]+\.[^:]+)(?:\:(\d),(\w+)?)?\z/
+
+ def set_status( tag, flag )
+ if m = MAIL_FILE.match(File.basename(@filename))
+ s, uniq, type, info, = m.to_a
+ return if type and type != '2' # do not change anything
+ newname = File.dirname(@filename) + '/' +
+ uniq + ':2,' + procinfostr(info.to_s, tag, flag)
+ else
+ newname = @filename + ':2,' + tag
+ end
+
+ File.link @filename, newname
+ File.unlink @filename
+ @filename = newname
+ end
+
+ def get_status( tag )
+ m = MAIL_FILE.match(File.basename(@filename)) or return false
+ m[2] == '2' and m[3].to_s.include?(tag[0])
+ end
+
+ end
+
+
+ ###
+ ### StringPort
+ ###
+
+ class StringPort < Port
+
+ def initialize( str = '' )
+ @buffer = str
+ super()
+ end
+
+ def string
+ @buffer
+ end
+
+ def to_s
+ @buffer.dup
+ end
+
+ alias read_all to_s
+
+ def size
+ @buffer.size
+ end
+
+ def ==( other )
+ StringPort === other and @buffer.equal? other.string
+ end
+
+ alias eql? ==
+
+ def hash
+ @buffer.id.hash
+ end
+
+ def inspect
+ "#<#{self.class}:id=#{sprintf '0x%x', @buffer.id}>"
+ end
+
+ def reproducible?
+ true
+ end
+
+ def ropen( &block )
+ @buffer or raise Errno::ENOENT, "#{inspect} is already removed"
+ StringInput.open(@buffer, &block)
+ end
+
+ def wopen( &block )
+ @buffer = ''
+ StringOutput.new(@buffer, &block)
+ end
+
+ def aopen( &block )
+ @buffer ||= ''
+ StringOutput.new(@buffer, &block)
+ end
+
+ def remove
+ @buffer = nil
+ end
+
+ alias rm remove
+
+ def copy_to( port )
+ port.wopen {|f|
+ f.write @buffer
+ }
+ end
+
+ alias cp copy_to
+
+ def move_to( port )
+ if StringPort === port
+ str = @buffer
+ port.instance_eval { @buffer = str }
+ else
+ copy_to port
+ end
+ remove
+ end
+
+ end
+
+end # module TMail
diff --git a/actionmailer/lib/action_mailer/vendor/tmail/scanner.rb b/actionmailer/lib/action_mailer/vendor/tmail/scanner.rb
new file mode 100755
index 0000000000..b602466d49
--- /dev/null
+++ b/actionmailer/lib/action_mailer/vendor/tmail/scanner.rb
@@ -0,0 +1,22 @@
+#
+# scanner.rb
+#
+# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
+#
+# This program is free software.
+# You can distribute/modify this program under the terms of
+# the GNU Lesser General Public License version 2 or later.
+#
+
+require 'tmail/utils'
+
+module TMail
+ require 'tmail/scanner_r.rb'
+ begin
+ raise LoadError, 'Turn off Ruby extention by user choice' if ENV['NORUBYEXT']
+ require 'tmail/scanner_c.so'
+ Scanner = Scanner_C
+ rescue LoadError
+ Scanner = Scanner_R
+ end
+end
diff --git a/actionmailer/lib/action_mailer/vendor/tmail/scanner_r.rb b/actionmailer/lib/action_mailer/vendor/tmail/scanner_r.rb
new file mode 100755
index 0000000000..fb90f9b5e9
--- /dev/null
+++ b/actionmailer/lib/action_mailer/vendor/tmail/scanner_r.rb
@@ -0,0 +1,244 @@
+#
+# scanner_r.rb
+#
+# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
+#
+# This program is free software.
+# You can distribute/modify this program under the terms of
+# the GNU Lesser General Public License version 2 or later.
+#
+
+require 'tmail/config'
+
+
+module TMail
+
+ class Scanner_R
+
+ Version = '0.10.7'
+ Version.freeze
+
+ MIME_HEADERS = {
+ :CTYPE => true,
+ :CENCODING => true,
+ :CDISPOSITION => true
+ }
+
+ alnum = 'a-zA-Z0-9'
+ atomsyms = %q[ _#!$%&`'*+-{|}~^/=? ].strip
+ tokensyms = %q[ _#!$%&`'*+-{|}~^. ].strip
+
+ atomchars = alnum + Regexp.quote(atomsyms)
+ tokenchars = alnum + Regexp.quote(tokensyms)
+ iso2022str = '\e(?!\(B)..(?:[^\e]+|\e(?!\(B)..)*\e\(B'
+
+ eucstr = '(?:[\xa1-\xfe][\xa1-\xfe])+'
+ sjisstr = '(?:[\x81-\x9f\xe0-\xef][\x40-\x7e\x80-\xfc])+'
+ utf8str = '(?:[\xc0-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf][\x80-\xbf])+'
+
+ quoted_with_iso2022 = /\A(?:[^\\\e"]+|#{iso2022str})+/n
+ domlit_with_iso2022 = /\A(?:[^\\\e\]]+|#{iso2022str})+/n
+ comment_with_iso2022 = /\A(?:[^\\\e()]+|#{iso2022str})+/n
+
+ quoted_without_iso2022 = /\A[^\\"]+/n
+ domlit_without_iso2022 = /\A[^\\\]]+/n
+ comment_without_iso2022 = /\A[^\\()]+/n
+
+ PATTERN_TABLE = {}
+ PATTERN_TABLE['EUC'] =
+ [
+ /\A(?:[#{atomchars}]+|#{iso2022str}|#{eucstr})+/n,
+ /\A(?:[#{tokenchars}]+|#{iso2022str}|#{eucstr})+/n,
+ quoted_with_iso2022,
+ domlit_with_iso2022,
+ comment_with_iso2022
+ ]
+ PATTERN_TABLE['SJIS'] =
+ [
+ /\A(?:[#{atomchars}]+|#{iso2022str}|#{sjisstr})+/n,
+ /\A(?:[#{tokenchars}]+|#{iso2022str}|#{sjisstr})+/n,
+ quoted_with_iso2022,
+ domlit_with_iso2022,
+ comment_with_iso2022
+ ]
+ PATTERN_TABLE['UTF8'] =
+ [
+ /\A(?:[#{atomchars}]+|#{utf8str})+/n,
+ /\A(?:[#{tokenchars}]+|#{utf8str})+/n,
+ quoted_without_iso2022,
+ domlit_without_iso2022,
+ comment_without_iso2022
+ ]
+ PATTERN_TABLE['NONE'] =
+ [
+ /\A[#{atomchars}]+/n,
+ /\A[#{tokenchars}]+/n,
+ quoted_without_iso2022,
+ domlit_without_iso2022,
+ comment_without_iso2022
+ ]
+
+
+ def initialize( str, scantype, comments )
+ init_scanner str
+ @comments = comments || []
+ @debug = false
+
+ # fix scanner mode
+ @received = (scantype == :RECEIVED)
+ @is_mime_header = MIME_HEADERS[scantype]
+
+ atom, token, @quoted_re, @domlit_re, @comment_re = PATTERN_TABLE[$KCODE]
+ @word_re = (MIME_HEADERS[scantype] ? token : atom)
+ end
+
+ attr_accessor :debug
+
+ def scan( &block )
+ if @debug
+ scan_main do |arr|
+ s, v = arr
+ printf "%7d %-10s %s\n",
+ rest_size(),
+ s.respond_to?(:id2name) ? s.id2name : s.inspect,
+ v.inspect
+ yield arr
+ end
+ else
+ scan_main(&block)
+ end
+ end
+
+ private
+
+ RECV_TOKEN = {
+ 'from' => :FROM,
+ 'by' => :BY,
+ 'via' => :VIA,
+ 'with' => :WITH,
+ 'id' => :ID,
+ 'for' => :FOR
+ }
+
+ def scan_main
+ until eof?
+ if skip(/\A[\n\r\t ]+/n) # LWSP
+ break if eof?
+ end
+
+ if s = readstr(@word_re)
+ if @is_mime_header
+ yield :TOKEN, s
+ else
+ # atom
+ if /\A\d+\z/ === s
+ yield :DIGIT, s
+ elsif @received
+ yield RECV_TOKEN[s.downcase] || :ATOM, s
+ else
+ yield :ATOM, s
+ end
+ end
+
+ elsif skip(/\A"/)
+ yield :QUOTED, scan_quoted_word()
+
+ elsif skip(/\A\[/)
+ yield :DOMLIT, scan_domain_literal()
+
+ elsif skip(/\A\(/)
+ @comments.push scan_comment()
+
+ else
+ c = readchar()
+ yield c, c
+ end
+ end
+
+ yield false, '$'
+ end
+
+ def scan_quoted_word
+ scan_qstr(@quoted_re, /\A"/, 'quoted-word')
+ end
+
+ def scan_domain_literal
+ '[' + scan_qstr(@domlit_re, /\A\]/, 'domain-literal') + ']'
+ end
+
+ def scan_qstr( pattern, terminal, type )
+ result = ''
+ until eof?
+ if s = readstr(pattern) then result << s
+ elsif skip(terminal) then return result
+ elsif skip(/\A\\/) then result << readchar()
+ else
+ raise "TMail FATAL: not match in #{type}"
+ end
+ end
+ scan_error! "found unterminated #{type}"
+ end
+
+ def scan_comment
+ result = ''
+ nest = 1
+ content = @comment_re
+
+ until eof?
+ if s = readstr(content) then result << s
+ elsif skip(/\A\)/) then nest -= 1
+ return result if nest == 0
+ result << ')'
+ elsif skip(/\A\(/) then nest += 1
+ result << '('
+ elsif skip(/\A\\/) then result << readchar()
+ else
+ raise 'TMail FATAL: not match in comment'
+ end
+ end
+ scan_error! 'found unterminated comment'
+ end
+
+ # string scanner
+
+ def init_scanner( str )
+ @src = str
+ end
+
+ def eof?
+ @src.empty?
+ end
+
+ def rest_size
+ @src.size
+ end
+
+ def readstr( re )
+ if m = re.match(@src)
+ @src = m.post_match
+ m[0]
+ else
+ nil
+ end
+ end
+
+ def readchar
+ readstr(/\A./)
+ end
+
+ def skip( re )
+ if m = re.match(@src)
+ @src = m.post_match
+ true
+ else
+ false
+ end
+ end
+
+ def scan_error!( msg )
+ raise SyntaxError, msg
+ end
+
+ end
+
+end # module TMail
diff --git a/actionmailer/lib/action_mailer/vendor/tmail/stringio.rb b/actionmailer/lib/action_mailer/vendor/tmail/stringio.rb
new file mode 100755
index 0000000000..24cf8a3a7c
--- /dev/null
+++ b/actionmailer/lib/action_mailer/vendor/tmail/stringio.rb
@@ -0,0 +1,260 @@
+#
+# stringio.rb
+#
+# Copyright (c) 1999-2003 Minero Aoki <aamine@loveruby.net>
+#
+# This program is free software.
+# You can distribute/modify this program under the terms of
+# the GNU Lesser General Public License version 2 or later.
+#
+# Id: stringio.rb,v 1.10 2003/04/27 22:02:14 aamine Exp
+#
+
+class StringInput#:nodoc:
+
+ include Enumerable
+
+ class << self
+
+ def new( str )
+ if block_given?
+ begin
+ f = super
+ yield f
+ ensure
+ f.close if f
+ end
+ else
+ super
+ end
+ end
+
+ alias open new
+
+ end
+
+ def initialize( str )
+ @src = str
+ @pos = 0
+ @closed = false
+ @lineno = 0
+ end
+
+ attr_reader :lineno
+
+ def string
+ @src
+ end
+
+ def inspect
+ "#<#{self.class}:#{@closed ? 'closed' : 'open'},src=#{@src[0,30].inspect}>"
+ end
+
+ def close
+ stream_check!
+ @pos = nil
+ @closed = true
+ end
+
+ def closed?
+ @closed
+ end
+
+ def pos
+ stream_check!
+ [@pos, @src.size].min
+ end
+
+ alias tell pos
+
+ def seek( offset, whence = IO::SEEK_SET )
+ stream_check!
+ case whence
+ when IO::SEEK_SET
+ @pos = offset
+ when IO::SEEK_CUR
+ @pos += offset
+ when IO::SEEK_END
+ @pos = @src.size - offset
+ else
+ raise ArgumentError, "unknown seek flag: #{whence}"
+ end
+ @pos = 0 if @pos < 0
+ @pos = [@pos, @src.size + 1].min
+ offset
+ end
+
+ def rewind
+ stream_check!
+ @pos = 0
+ end
+
+ def eof?
+ stream_check!
+ @pos > @src.size
+ end
+
+ def each( &block )
+ stream_check!
+ begin
+ @src.each(&block)
+ ensure
+ @pos = 0
+ end
+ end
+
+ def gets
+ stream_check!
+ if idx = @src.index(?\n, @pos)
+ idx += 1 # "\n".size
+ line = @src[ @pos ... idx ]
+ @pos = idx
+ @pos += 1 if @pos == @src.size
+ else
+ line = @src[ @pos .. -1 ]
+ @pos = @src.size + 1
+ end
+ @lineno += 1
+
+ line
+ end
+
+ def getc
+ stream_check!
+ ch = @src[@pos]
+ @pos += 1
+ @pos += 1 if @pos == @src.size
+ ch
+ end
+
+ def read( len = nil )
+ stream_check!
+ return read_all unless len
+ str = @src[@pos, len]
+ @pos += len
+ @pos += 1 if @pos == @src.size
+ str
+ end
+
+ alias sysread read
+
+ def read_all
+ stream_check!
+ return nil if eof?
+ rest = @src[@pos ... @src.size]
+ @pos = @src.size + 1
+ rest
+ end
+
+ def stream_check!
+ @closed and raise IOError, 'closed stream'
+ end
+
+end
+
+
+class StringOutput#:nodoc:
+
+ class << self
+
+ def new( str = '' )
+ if block_given?
+ begin
+ f = super
+ yield f
+ ensure
+ f.close if f
+ end
+ else
+ super
+ end
+ end
+
+ alias open new
+
+ end
+
+ def initialize( str = '' )
+ @dest = str
+ @closed = false
+ end
+
+ def close
+ @closed = true
+ end
+
+ def closed?
+ @closed
+ end
+
+ def string
+ @dest
+ end
+
+ alias value string
+ alias to_str string
+
+ def size
+ @dest.size
+ end
+
+ alias pos size
+
+ def inspect
+ "#<#{self.class}:#{@dest ? 'open' : 'closed'},#{id}>"
+ end
+
+ def print( *args )
+ stream_check!
+ raise ArgumentError, 'wrong # of argument (0 for >1)' if args.empty?
+ args.each do |s|
+ raise ArgumentError, 'nil not allowed' if s.nil?
+ @dest << s.to_s
+ end
+ nil
+ end
+
+ def puts( *args )
+ stream_check!
+ args.each do |str|
+ @dest << (s = str.to_s)
+ @dest << "\n" unless s[-1] == ?\n
+ end
+ @dest << "\n" if args.empty?
+ nil
+ end
+
+ def putc( ch )
+ stream_check!
+ @dest << ch.chr
+ nil
+ end
+
+ def printf( *args )
+ stream_check!
+ @dest << sprintf(*args)
+ nil
+ end
+
+ def write( str )
+ stream_check!
+ s = str.to_s
+ @dest << s
+ s.size
+ end
+
+ alias syswrite write
+
+ def <<( str )
+ stream_check!
+ @dest << str.to_s
+ self
+ end
+
+ private
+
+ def stream_check!
+ @closed and raise IOError, 'closed stream'
+ end
+
+end
diff --git a/actionmailer/lib/action_mailer/vendor/tmail/tmail.rb b/actionmailer/lib/action_mailer/vendor/tmail/tmail.rb
new file mode 100755
index 0000000000..57ed3cc581
--- /dev/null
+++ b/actionmailer/lib/action_mailer/vendor/tmail/tmail.rb
@@ -0,0 +1 @@
+require 'tmail'
diff --git a/actionmailer/lib/action_mailer/vendor/tmail/utils.rb b/actionmailer/lib/action_mailer/vendor/tmail/utils.rb
new file mode 100755
index 0000000000..4f603b96b9
--- /dev/null
+++ b/actionmailer/lib/action_mailer/vendor/tmail/utils.rb
@@ -0,0 +1,215 @@
+#
+# utils.rb
+#
+# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
+#
+# This program is free software.
+# You can distribute/modify this program under the terms of
+# the GNU Lesser General Public License version 2 or later.
+#
+
+module TMail
+
+ class SyntaxError < StandardError; end
+
+
+ def TMail.new_boundary
+ 'mimepart_' + random_tag
+ end
+
+ def TMail.new_message_id( fqdn = nil )
+ fqdn ||= ::Socket.gethostname
+ "<#{random_tag()}@#{fqdn}.tmail>"
+ end
+
+ def TMail.random_tag
+ @uniq += 1
+ t = Time.now
+ sprintf('%x%x_%x%x%d%x',
+ t.to_i, t.tv_usec,
+ $$, Thread.current.id, @uniq, rand(255))
+ end
+ private_class_method :random_tag
+
+ @uniq = 0
+
+
+ module TextUtils
+
+ aspecial = '()<>[]:;.@\\,"'
+ tspecial = '()<>[];:@\\,"/?='
+ lwsp = " \t\r\n"
+ control = '\x00-\x1f\x7f-\xff'
+
+ ATOM_UNSAFE = /[#{Regexp.quote aspecial}#{control}#{lwsp}]/n
+ PHRASE_UNSAFE = /[#{Regexp.quote aspecial}#{control}]/n
+ TOKEN_UNSAFE = /[#{Regexp.quote tspecial}#{control}#{lwsp}]/n
+ CONTROL_CHAR = /[#{control}]/n
+
+ def atom_safe?( str )
+ not ATOM_UNSAFE === str
+ end
+
+ def quote_atom( str )
+ (ATOM_UNSAFE === str) ? dquote(str) : str
+ end
+
+ def quote_phrase( str )
+ (PHRASE_UNSAFE === str) ? dquote(str) : str
+ end
+
+ def token_safe?( str )
+ not TOKEN_UNSAFE === str
+ end
+
+ def quote_token( str )
+ (TOKEN_UNSAFE === str) ? dquote(str) : str
+ end
+
+ def dquote( str )
+ '"' + str.gsub(/["\\]/n) {|s| '\\' + s } + '"'
+ end
+ private :dquote
+
+
+ def join_domain( arr )
+ arr.map {|i|
+ if /\A\[.*\]\z/ === i
+ i
+ else
+ quote_atom(i)
+ end
+ }.join('.')
+ end
+
+
+ ZONESTR_TABLE = {
+ 'jst' => 9 * 60,
+ 'eet' => 2 * 60,
+ 'bst' => 1 * 60,
+ 'met' => 1 * 60,
+ 'gmt' => 0,
+ 'utc' => 0,
+ 'ut' => 0,
+ 'nst' => -(3 * 60 + 30),
+ 'ast' => -4 * 60,
+ 'edt' => -4 * 60,
+ 'est' => -5 * 60,
+ 'cdt' => -5 * 60,
+ 'cst' => -6 * 60,
+ 'mdt' => -6 * 60,
+ 'mst' => -7 * 60,
+ 'pdt' => -7 * 60,
+ 'pst' => -8 * 60,
+ 'a' => -1 * 60,
+ 'b' => -2 * 60,
+ 'c' => -3 * 60,
+ 'd' => -4 * 60,
+ 'e' => -5 * 60,
+ 'f' => -6 * 60,
+ 'g' => -7 * 60,
+ 'h' => -8 * 60,
+ 'i' => -9 * 60,
+ # j not use
+ 'k' => -10 * 60,
+ 'l' => -11 * 60,
+ 'm' => -12 * 60,
+ 'n' => 1 * 60,
+ 'o' => 2 * 60,
+ 'p' => 3 * 60,
+ 'q' => 4 * 60,
+ 'r' => 5 * 60,
+ 's' => 6 * 60,
+ 't' => 7 * 60,
+ 'u' => 8 * 60,
+ 'v' => 9 * 60,
+ 'w' => 10 * 60,
+ 'x' => 11 * 60,
+ 'y' => 12 * 60,
+ 'z' => 0 * 60
+ }
+
+ def timezone_string_to_unixtime( str )
+ if m = /([\+\-])(\d\d?)(\d\d)/.match(str)
+ sec = (m[2].to_i * 60 + m[3].to_i) * 60
+ m[1] == '-' ? -sec : sec
+ else
+ min = ZONESTR_TABLE[str.downcase] or
+ raise SyntaxError, "wrong timezone format '#{str}'"
+ min * 60
+ end
+ end
+
+
+ WDAY = %w( Sun Mon Tue Wed Thu Fri Sat TMailBUG )
+ MONTH = %w( TMailBUG Jan Feb Mar Apr May Jun
+ Jul Aug Sep Oct Nov Dec TMailBUG )
+
+ def time2str( tm )
+ # [ruby-list:7928]
+ gmt = Time.at(tm.to_i)
+ gmt.gmtime
+ offset = tm.to_i - Time.local(*gmt.to_a[0,6].reverse).to_i
+
+ # DO NOT USE strftime: setlocale() breaks it
+ sprintf '%s, %s %s %d %02d:%02d:%02d %+.2d%.2d',
+ WDAY[tm.wday], tm.mday, MONTH[tm.month],
+ tm.year, tm.hour, tm.min, tm.sec,
+ *(offset / 60).divmod(60)
+ end
+
+
+ MESSAGE_ID = /<[^\@>]+\@[^>\@]+>/
+
+ def message_id?( str )
+ MESSAGE_ID === str
+ end
+
+
+ MIME_ENCODED = /=\?[^\s?=]+\?[QB]\?[^\s?=]+\?=/i
+
+ def mime_encoded?( str )
+ MIME_ENCODED === str
+ end
+
+
+ def decode_params( hash )
+ new = Hash.new
+ encoded = nil
+ hash.each do |key, value|
+ if m = /\*(?:(\d+)\*)?\z/.match(key)
+ ((encoded ||= {})[m.pre_match] ||= [])[(m[1] || 0).to_i] = value
+ else
+ new[key] = to_kcode(value)
+ end
+ end
+ if encoded
+ encoded.each do |key, strings|
+ new[key] = decode_RFC2231(strings.join(''))
+ end
+ end
+
+ new
+ end
+
+ NKF_FLAGS = {
+ 'EUC' => '-e -m',
+ 'SJIS' => '-s -m'
+ }
+
+ def to_kcode( str )
+ flag = NKF_FLAGS[$KCODE] or return str
+ NKF.nkf(flag, str)
+ end
+
+ RFC2231_ENCODED = /\A(?:iso-2022-jp|euc-jp|shift_jis|us-ascii)?'[a-z]*'/in
+
+ def decode_RFC2231( str )
+ m = RFC2231_ENCODED.match(str) or return str
+ NKF.nkf(NKF_FLAGS[$KCODE],
+ m.post_match.gsub(/%[\da-f]{2}/in) {|s| s[1,2].hex.chr })
+ end
+
+ end
+
+end
diff --git a/actionmailer/test/fixtures/templates/signed_up.rhtml b/actionmailer/test/fixtures/templates/signed_up.rhtml
new file mode 100644
index 0000000000..a85d5fa442
--- /dev/null
+++ b/actionmailer/test/fixtures/templates/signed_up.rhtml
@@ -0,0 +1,3 @@
+Hello there,
+
+Mr. <%= @recipient %> \ No newline at end of file
diff --git a/actionmailer/test/fixtures/test_mailer/signed_up.rhtml b/actionmailer/test/fixtures/test_mailer/signed_up.rhtml
new file mode 100644
index 0000000000..a85d5fa442
--- /dev/null
+++ b/actionmailer/test/fixtures/test_mailer/signed_up.rhtml
@@ -0,0 +1,3 @@
+Hello there,
+
+Mr. <%= @recipient %> \ No newline at end of file
diff --git a/actionmailer/test/mail_service_test.rb b/actionmailer/test/mail_service_test.rb
new file mode 100755
index 0000000000..adc5be2fe9
--- /dev/null
+++ b/actionmailer/test/mail_service_test.rb
@@ -0,0 +1,92 @@
+$:.unshift(File.dirname(__FILE__) + "/../lib/")
+
+require 'test/unit'
+require 'action_mailer'
+
+class TestMailer < ActionMailer::Base
+ def signed_up(recipient)
+ @recipients = recipient
+ @subject = "[Signed up] Welcome #{recipient}"
+ @from = "system@loudthinking.com"
+ @sent_on = Time.local(2004, 12, 12)
+ @body["recipient"] = recipient
+ end
+
+ def cancelled_account(recipient)
+ @recipients = recipient
+ @subject = "[Cancelled] Goodbye #{recipient}"
+ @from = "system@loudthinking.com"
+ @sent_on = Time.local(2004, 12, 12)
+ @body = "Goodbye, Mr. #{recipient}"
+ end
+end
+
+TestMailer.template_root = File.dirname(__FILE__) + "/fixtures"
+
+class ActionMailerTest < Test::Unit::TestCase
+ def setup
+ ActionMailer::Base.delivery_method = :test
+ ActionMailer::Base.perform_deliveries = true
+ ActionMailer::Base.deliveries = []
+
+ @recipient = 'test@localhost'
+ end
+
+ def test_signed_up
+ expected = TMail::Mail.new
+ expected.to = @recipient
+ expected.subject = "[Signed up] Welcome #{@recipient}"
+ expected.body = "Hello there, \n\nMr. #{@recipient}"
+ expected.from = "system@loudthinking.com"
+ expected.date = Time.local(2004, 12, 12)
+
+ created = nil
+ assert_nothing_raised { created = TestMailer.create_signed_up(@recipient) }
+ assert_not_nil created
+ assert_equal expected.encoded, created.encoded
+
+ assert_nothing_raised { TestMailer.deliver_signed_up(@recipient) }
+ assert_not_nil ActionMailer::Base.deliveries.first
+ assert_equal expected.encoded, ActionMailer::Base.deliveries.first.encoded
+ end
+
+ def test_cancelled_account
+ expected = TMail::Mail.new
+ expected.to = @recipient
+ expected.subject = "[Cancelled] Goodbye #{@recipient}"
+ expected.body = "Goodbye, Mr. #{@recipient}"
+ expected.from = "system@loudthinking.com"
+ expected.date = Time.local(2004, 12, 12)
+
+ created = nil
+ assert_nothing_raised { created = TestMailer.create_cancelled_account(@recipient) }
+ assert_not_nil created
+ assert_equal expected.encoded, created.encoded
+
+ assert_nothing_raised { TestMailer.deliver_cancelled_account(@recipient) }
+ assert_not_nil ActionMailer::Base.deliveries.first
+ assert_equal expected.encoded, ActionMailer::Base.deliveries.first.encoded
+ end
+
+ def test_instances_are_nil
+ assert_nil ActionMailer::Base.new
+ assert_nil TestMailer.new
+ end
+
+ def test_deliveries_array
+ assert_not_nil ActionMailer::Base.deliveries
+ assert_equal 0, ActionMailer::Base.deliveries.size
+ TestMailer.deliver_signed_up(@recipient)
+ assert_equal 1, ActionMailer::Base.deliveries.size
+ assert_not_nil ActionMailer::Base.deliveries.first
+ end
+
+ def test_perform_deliveries_flag
+ ActionMailer::Base.perform_deliveries = false
+ TestMailer.deliver_signed_up(@recipient)
+ assert_equal 0, ActionMailer::Base.deliveries.size
+ ActionMailer::Base.perform_deliveries = true
+ TestMailer.deliver_signed_up(@recipient)
+ assert_equal 1, ActionMailer::Base.deliveries.size
+ end
+end