aboutsummaryrefslogtreecommitdiffstats
path: root/actionmailer/lib/action_mailer
diff options
context:
space:
mode:
Diffstat (limited to 'actionmailer/lib/action_mailer')
-rw-r--r--actionmailer/lib/action_mailer/base.rb795
-rw-r--r--actionmailer/lib/action_mailer/collector.rb36
-rw-r--r--actionmailer/lib/action_mailer/delivery_method.rb56
-rw-r--r--actionmailer/lib/action_mailer/delivery_method/file.rb21
-rw-r--r--actionmailer/lib/action_mailer/delivery_method/sendmail.rb22
-rw-r--r--actionmailer/lib/action_mailer/delivery_method/smtp.rb30
-rw-r--r--actionmailer/lib/action_mailer/delivery_method/test.rb12
-rw-r--r--actionmailer/lib/action_mailer/delivery_methods.rb90
-rw-r--r--actionmailer/lib/action_mailer/deprecated_api.rb139
-rw-r--r--actionmailer/lib/action_mailer/deprecated_body.rb46
-rw-r--r--actionmailer/lib/action_mailer/mail_helper.rb9
-rw-r--r--actionmailer/lib/action_mailer/old_api.rb248
-rw-r--r--actionmailer/lib/action_mailer/railtie.rb17
-rw-r--r--actionmailer/lib/action_mailer/test_case.rb2
-rw-r--r--actionmailer/lib/action_mailer/test_helper.rb1
-rw-r--r--actionmailer/lib/action_mailer/tmail_compat.rb12
-rwxr-xr-xactionmailer/lib/action_mailer/vendor/text-format-0.6.3/text/format.rb1467
-rw-r--r--actionmailer/lib/action_mailer/vendor/text_format.rb10
18 files changed, 907 insertions, 2106 deletions
diff --git a/actionmailer/lib/action_mailer/base.rb b/actionmailer/lib/action_mailer/base.rb
index 356861b591..6246530bf0 100644
--- a/actionmailer/lib/action_mailer/base.rb
+++ b/actionmailer/lib/action_mailer/base.rb
@@ -1,6 +1,11 @@
require 'active_support/core_ext/class'
+require 'active_support/core_ext/object/blank'
+require 'active_support/core_ext/array/uniq_by'
+require 'active_support/core_ext/module/delegation'
+require 'active_support/core_ext/string/inflections'
require 'mail'
require 'action_mailer/tmail_compat'
+require 'action_mailer/collector'
module ActionMailer #:nodoc:
# Action Mailer allows you to send email from your application using a mailer model and views.
@@ -11,46 +16,76 @@ module ActionMailer #:nodoc:
#
# $ script/generate mailer Notifier
#
- # The generated model inherits from ActionMailer::Base. Emails are defined by creating methods within the model which are then
- # used to set variables to be used in the mail template, to change options on the mail, or
- # to add attachments.
+ # The generated model inherits from ActionMailer::Base. Emails are defined by creating methods
+ # within the model which are then used to set variables to be used in the mail template, to
+ # change options on the mail, or to add attachments.
#
# Examples:
#
# class Notifier < ActionMailer::Base
- # def signup_notification(recipient)
- # recipients recipient.email_address_with_name
- # bcc ["bcc@example.com", "Order Watcher <watcher@example.com>"]
- # from "system@example.com"
- # subject "New account information"
- # body :account => recipient
+ # default :from => 'no-reply@example.com',
+ # :return_path => 'system@example.com'
+ #
+ # def welcome(recipient)
+ # @account = recipient
+ # mail(:to => recipient.email_address_with_name,
+ # :bcc => ["bcc@example.com", "Order Watcher <watcher@example.com>"])
+ # end
# end
- # end
+ #
+ # Within the mailer method, you have access to the following methods:
+ #
+ # * <tt>attachments[]=</tt> - Allows you to add attachments to your email in an intuitive
+ # manner; <tt>attachments['filename.png'] = File.read('path/to/filename.png')</tt>
+ #
+ # * <tt>headers[]=</tt> - Allows you to specify non standard headers in your email such
+ # as <tt>headers['X-No-Spam'] = 'True'</tt>
+ #
+ # * <tt>headers(hash)</tt> - Allows you to specify multiple headers in your email such
+ # as <tt>headers({'X-No-Spam' => 'True', 'In-Reply-To' => '1234@message.id'})</tt>
+ #
+ # * <tt>mail</tt> - Allows you to specify your email to send.
+ #
+ # The hash passed to the mail method allows you to specify any header that a Mail::Message
+ # will accept (any valid Email header including optional fields). Obviously if you specify
+ # the same header in the headers method and then again in the mail method, the last one
+ # will over write the first, unless you are specifying a header field that can appear more
+ # than once per RFC, in which case, both will be inserted (X-value headers for example can
+ # appear multiple times.)
+ #
+ # The mail method, if not passed a block, will inspect your views and send all the views with
+ # the same name as the method, so the above action would send the +welcome.plain.erb+ view file
+ # as well as the +welcome.html.erb+ view file in a +multipart/alternative+ email.
+ #
+ # If you want to explicitly render only certain templates, pass a block:
+ #
+ # mail(:to => user.emai) do |format|
+ # format.text
+ # format.html
+ # end
#
- # Mailer methods have the following configuration methods available.
+ # The block syntax is useful if also need to specify information specific to a part:
#
- # * <tt>recipients</tt> - Takes one or more email addresses. These addresses are where your email will be delivered to. Sets the <tt>To:</tt> header.
- # * <tt>subject</tt> - The subject of your email. Sets the <tt>Subject:</tt> header.
- # * <tt>from</tt> - Who the email you are sending is from. Sets the <tt>From:</tt> header.
- # * <tt>cc</tt> - Takes one or more email addresses. These addresses will receive a carbon copy of your email. Sets the <tt>Cc:</tt> header.
- # * <tt>bcc</tt> - Takes one or more email addresses. These addresses will receive a blind carbon copy of your email. Sets the <tt>Bcc:</tt> header.
- # * <tt>reply_to</tt> - Takes one or more email addresses. These addresses will be listed as the default recipients when replying to your email. Sets the <tt>Reply-To:</tt> header.
- # * <tt>sent_on</tt> - The date on which the message was sent. If not set, the header will be set by the delivery agent.
- # * <tt>content_type</tt> - Specify the content type of the message. Defaults to <tt>text/plain</tt>.
- # * <tt>headers</tt> - Specify additional headers to be set for the message, e.g. <tt>headers 'X-Mail-Count' => 107370</tt>.
+ # mail(:to => user.emai) do |format|
+ # format.text(:content_transfer_encoding => "base64")
+ # format.html
+ # end
#
- # When a <tt>headers 'return-path'</tt> is specified, that value will be used as the 'envelope from'
- # address. Setting this is useful when you want delivery notifications sent to a different address than
- # the one in <tt>from</tt>.
+ # Or even to renderize a special view:
#
+ # mail(:to => user.emai) do |format|
+ # format.text
+ # format.html { render "some_other_template" }
+ # end
#
# = Mailer views
#
- # Like Action Controller, each mailer class has a corresponding view directory
- # in which each method of the class looks for a template with its name.
- # To define a template to be used with a mailing, create an <tt>.erb</tt> file with the same name as the method
- # in your mailer model. For example, in the mailer defined above, the template at
- # <tt>app/views/notifier/signup_notification.erb</tt> would be used to generate the email.
+ # Like Action Controller, each mailer class has a corresponding view directory in which each
+ # method of the class looks for a template with its name.
+ #
+ # To define a template to be used with a mailing, create an <tt>.erb</tt> file with the same
+ # name as the method in your mailer model. For example, in the mailer defined above, the template at
+ # <tt>app/views/notifier/signup_notification.text.erb</tt> would be used to generate the email.
#
# Variables defined in the model are accessible as instance variables in the view.
#
@@ -64,9 +99,9 @@ module ActionMailer #:nodoc:
# You got a new note!
# <%= truncate(@note.body, 25) %>
#
- # If you need to access the subject, from or the recipients in the view, you can do that through mailer object:
+ # If you need to access the subject, from or the recipients in the view, you can do that through message object:
#
- # You got a new note from <%= mailer.from %>!
+ # You got a new note from <%= message.from %>!
# <%= truncate(@note.body, 25) %>
#
#
@@ -106,54 +141,13 @@ module ActionMailer #:nodoc:
# Once a mailer action and template are defined, you can deliver your message or create it and save it
# for delivery later:
#
- # Notifier.deliver_signup_notification(david) # sends the email
- # mail = Notifier.create_signup_notification(david) # => a tmail object
- # Notifier.deliver(mail)
- #
- # You never instantiate your mailer class. Rather, your delivery instance
- # methods are automatically wrapped in class methods that start with the word
- # <tt>deliver_</tt> followed by the name of the mailer method that you would
- # like to deliver. The <tt>signup_notification</tt> method defined above is
- # delivered by invoking <tt>Notifier.deliver_signup_notification</tt>.
+ # Notifier.welcome(david).deliver # sends the email
+ # mail = Notifier.welcome(david) # => a Mail::Message object
+ # mail.deliver # sends the email
#
+ # You never instantiate your mailer class. Rather, you just call the method on the class itself.
#
- # = HTML email
- #
- # To send mail as HTML, make sure your view (the <tt>.erb</tt> file) generates HTML and
- # set the content type to html.
- #
- # class MyMailer < ActionMailer::Base
- # def signup_notification(recipient)
- # recipients recipient.email_address_with_name
- # subject "New account information"
- # from "system@example.com"
- # body :account => recipient
- # content_type "text/html"
- # end
- # end
- #
- #
- # = Multipart email
- #
- # You can explicitly specify multipart messages:
- #
- # class ApplicationMailer < ActionMailer::Base
- # def signup_notification(recipient)
- # recipients recipient.email_address_with_name
- # subject "New account information"
- # from "system@example.com"
- # content_type "multipart/alternative"
- # body :account => recipient
- #
- # part :content_type => "text/html",
- # :data => render_message("signup-as-html")
- #
- # part "text/plain" do |p|
- # p.body = render_message("signup-as-plain")
- # p.content_transfer_encoding = "base64"
- # end
- # end
- # end
+ # = Multipart Emails
#
# Multipart messages can also be used implicitly because Action Mailer will automatically
# detect and use multipart templates, where each template is named after the name of the action, followed
@@ -163,13 +157,12 @@ module ActionMailer #:nodoc:
# * signup_notification.text.plain.erb
# * signup_notification.text.html.erb
# * signup_notification.text.xml.builder
- # * signup_notification.text.x-yaml.erb
+ # * signup_notification.text.yaml.erb
#
- # Each would be rendered and added as a separate part to the message,
- # with the corresponding content type. The content type for the entire
- # message is automatically set to <tt>multipart/alternative</tt>, which indicates
- # that the email contains multiple different representations of the same email
- # body. The same body hash is passed to each template.
+ # Each would be rendered and added as a separate part to the message, with the corresponding content
+ # type. The content type for the entire message is automatically set to <tt>multipart/alternative</tt>,
+ # which indicates that the email contains multiple different representations of the same email
+ # body. The same instance variables defined in the action are passed to all email templates.
#
# Implicit template rendering is not performed if any attachments or parts have been added to the email.
# This means that you'll have to manually add each part to the email and set the content type of the email
@@ -177,32 +170,35 @@ module ActionMailer #:nodoc:
#
# = Attachments
#
- # Attachments can be added by using the +attachment+ method.
- #
- # Example:
+ # You can see above how to make a multipart HTML / Text email, to send attachments is just
+ # as easy:
#
# class ApplicationMailer < ActionMailer::Base
- # # attachments
- # def signup_notification(recipient)
- # recipients recipient.email_address_with_name
- # subject "New account information"
- # from "system@example.com"
- #
- # attachment :content_type => "image/jpeg",
- # :body => File.read("an-image.jpg")
- #
- # attachment "application/pdf" do |a|
- # a.body = generate_your_pdf_here()
- # end
+ # def welcome(recipient)
+ # attachments['free_book.pdf'] = { :data => File.read('path/to/file.pdf') }
+ # mail(:to => recipient, :subject => "New account information")
# end
# end
+ #
+ # Which will (if it had both a <tt>.text.erb</tt> and <tt>.html.erb</tt> tempalte in the view
+ # directory), send a complete <tt>multipart/mixed</tt> email with two parts, the first part being
+ # a <tt>multipart/alternative</tt> with the text and HTML email parts inside, and the second being
+ # a <tt>application/pdf</tt> with a Base64 encoded copy of the file.pdf book with the filename
+ # +free_book.pdf+.
#
#
# = Configuration options
#
# These options are specified on the class level, like <tt>ActionMailer::Base.template_root = "/my/templates"</tt>
#
- # * <tt>template_root</tt> - Determines the base from which template references will be made.
+ # * <tt>default</tt> - This is a class wide hash of <tt>:key => value</tt> pairs containing
+ # default values for the specified header fields of the <tt>Mail::Message</tt>. You can
+ # specify a default for any valid header for <tt>Mail::Message</tt> and it will be used if
+ # you do not override it. The defaults set by Action Mailer are:
+ # * <tt>:mime_version => "1.0"</tt>
+ # * <tt>:charset => "utf-8",</tt>
+ # * <tt>:content_type => "text/plain",</tt>
+ # * <tt>:parts_order => [ "text/plain", "text/enriched", "text/html" ]</tt>
#
# * <tt>logger</tt> - 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.
@@ -236,23 +232,22 @@ module ActionMailer #:nodoc:
# * <tt>deliveries</tt> - Keeps an array of all the emails sent out through the Action Mailer with <tt>delivery_method :test</tt>. Most useful
# for unit and functional testing.
#
- # * <tt>default_charset</tt> - The default charset used for the body and to encode the subject. Defaults to UTF-8. You can also
- # pick a different charset from inside a method with +charset+.
+ # * <tt>default_charset</tt> - This is now deprecated, use the +default+ method above to
+ # set the default +:charset+.
#
- # * <tt>default_content_type</tt> - The default content type used for the main part of the message. Defaults to "text/plain". You
- # can also pick a different content type from inside a method with +content_type+.
+ # * <tt>default_content_type</tt> - This is now deprecated, use the +default+ method above
+ # to set the default +:content_type+.
#
- # * <tt>default_mime_version</tt> - The default mime version used for the message. Defaults to <tt>1.0</tt>. You
- # can also pick a different value from inside a method with +mime_version+.
+ # * <tt>default_mime_version</tt> - This is now deprecated, use the +default+ method above
+ # to set the default +:mime_version+.
#
- # * <tt>default_implicit_parts_order</tt> - When a message is built implicitly (i.e. multiple parts are assembled from templates
- # which specify the content type in their filenames) this variable controls how the parts are ordered. Defaults to
- # <tt>["text/html", "text/enriched", "text/plain"]</tt>. Items that appear first in the array have higher priority in the mail client
- # and appear last in the mime encoded message. You can also pick a different order from inside a method with
- # +implicit_parts_order+.
+ # * <tt>default_implicit_parts_order</tt> - This is now deprecated, use the +default+ method above
+ # to set the default +:parts_order+. Parts Order is used when a message is built implicitly
+ # (i.e. multiple parts are assembled from templates which specify the content type in their
+ # filenames) this variable controls how the parts are ordered.
class Base < AbstractController::Base
- include Quoting
- extend AdvAttrAccessor
+ include DeliveryMethods, Quoting
+ abstract!
include AbstractController::Logger
include AbstractController::Rendering
@@ -260,131 +255,34 @@ module ActionMailer #:nodoc:
include AbstractController::Layouts
include AbstractController::Helpers
include AbstractController::UrlFor
+ include AbstractController::Translation
helper ActionMailer::MailHelper
- include ActionMailer::DeprecatedBody
-
- private_class_method :new #:nodoc:
-
- @@raise_delivery_errors = true
- cattr_accessor :raise_delivery_errors
-
- @@perform_deliveries = true
- cattr_accessor :perform_deliveries
-
- @@deliveries = []
- cattr_accessor :deliveries
-
- @@default_charset = "utf-8"
- cattr_accessor :default_charset
-
- @@default_content_type = "text/plain"
- cattr_accessor :default_content_type
-
- @@default_mime_version = "1.0"
- cattr_accessor :default_mime_version
-
- # This specifies the order that the parts of a multipart email will be. Usually you put
- # text/plain at the top so someone without a MIME capable email reader can read the plain
- # text of your email first.
- #
- # Any content type that is not listed here will be inserted in the order you add them to
- # the email after the content types you list here.
- @@default_implicit_parts_order = [ "text/plain", "text/enriched", "text/html" ]
- cattr_accessor :default_implicit_parts_order
-
- @@protected_instance_variables = %w(@parts @mail)
- cattr_reader :protected_instance_variables
-
- # Specify the BCC addresses for the message
- adv_attr_accessor :bcc
-
- # Specify the CC addresses for the message.
- adv_attr_accessor :cc
- # Specify the charset to use for the message. This defaults to the
- # +default_charset+ specified for ActionMailer::Base.
- adv_attr_accessor :charset
+ include ActionMailer::OldApi
+ include ActionMailer::DeprecatedApi
- # Specify the content type for the message. This defaults to <tt>text/plain</tt>
- # in most cases, but can be automatically set in some situations.
- adv_attr_accessor :content_type
-
- # Specify the from address for the message.
- adv_attr_accessor :from
-
- # Specify the address (if different than the "from" address) to direct
- # replies to this message.
- adv_attr_accessor :reply_to
-
- # Specify additional headers to be added to the message.
- adv_attr_accessor :headers
-
- # Specify the order in which parts should be sorted, based on content-type.
- # This defaults to the value for the +default_implicit_parts_order+.
- adv_attr_accessor :implicit_parts_order
-
- # Defaults to "1.0", but may be explicitly given if needed.
- adv_attr_accessor :mime_version
-
- # The recipient addresses for the message, either as a string (for a single
- # address) or an array (for multiple addresses).
- adv_attr_accessor :recipients
-
- # The date on which the message was sent. If not set (the default), the
- # header will be set by the delivery agent.
- adv_attr_accessor :sent_on
-
- # Specify the subject of the message.
- adv_attr_accessor :subject
-
- # Specify the template name to use for current message. This is the "base"
- # template name, without the extension or directory, and may be used to
- # have multiple mailer methods share the same template.
- adv_attr_accessor :template
-
- # Override the mailer name, which defaults to an inflected version of the
- # mailer's class name. If you want to use a template in a non-standard
- # location, you can use this to specify that location.
- adv_attr_accessor :mailer_name
-
- # Expose the internal mail
- attr_reader :mail
+ private_class_method :new #:nodoc:
- # Alias controller_path to mailer_name so render :partial in views work.
- alias :controller_path :mailer_name
+ extlib_inheritable_accessor :default_params
+ self.default_params = {
+ :mime_version => "1.0",
+ :charset => "utf-8",
+ :content_type => "text/plain",
+ :parts_order => [ "text/plain", "text/enriched", "text/html" ]
+ }
class << self
- attr_writer :mailer_name
-
- delegate :settings, :settings=, :to => ActionMailer::DeliveryMethod::File, :prefix => :file
- delegate :settings, :settings=, :to => ActionMailer::DeliveryMethod::Sendmail, :prefix => :sendmail
- delegate :settings, :settings=, :to => ActionMailer::DeliveryMethod::Smtp, :prefix => :smtp
def mailer_name
@mailer_name ||= name.underscore
end
+ attr_writer :mailer_name
alias :controller_path :mailer_name
- def delivery_method=(method_name)
- @delivery_method = ActionMailer::DeliveryMethod.lookup_method(method_name)
- end
-
- def respond_to?(method_symbol, include_private = false) #:nodoc:
- matches_dynamic_method?(method_symbol) || super
- end
-
- def method_missing(method_symbol, *parameters) #:nodoc:
- if match = matches_dynamic_method?(method_symbol)
- case match[1]
- when 'create' then new(match[2], *parameters).mail
- when 'deliver' then new(match[2], *parameters).deliver!
- when 'new' then nil
- else super
- end
- else
- super
- end
+ def default(value=nil)
+ self.default_params.merge!(value) if value
+ self.default_params
end
# Receives a raw email, parses it into an email object, decodes it,
@@ -406,26 +304,24 @@ module ActionMailer #:nodoc:
end
end
- # Deliver the given mail object directly. This can be used to deliver
- # a preconstructed mail object, like:
- #
- # email = MyMailer.create_some_mail(parameters)
- # email.set_some_obscure_header "frobnicate"
- # MyMailer.deliver(email)
- def deliver(mail)
- new.deliver!(mail)
+ # Delivers a mail object. This is actually called by the <tt>Mail::Message</tt> object
+ # itself through a call back when you call <tt>:deliver</tt> on the Mail::Message,
+ # calling +deliver_mail+ directly and passing an Mail::Message will do nothing.
+ def deliver_mail(mail) #:nodoc:
+ ActiveSupport::Notifications.instrument("action_mailer.deliver") do |payload|
+ self.set_payload_for_mail(payload, mail)
+ yield # Let Mail do the delivery actions
+ end
end
- def template_root
- self.view_paths && self.view_paths.first
+ def respond_to?(method, *args) #:nodoc:
+ super || action_methods.include?(method.to_s)
end
- # Should template root overwrite the whole view_paths?
- def template_root=(root)
- self.view_paths = ActionView::Base.process_view_paths(root)
- end
+ protected
def set_payload_for_mail(payload, mail) #:nodoc:
+ payload[:mailer] = self.name
payload[:message_id] = mail.message_id
payload[:subject] = mail.subject
payload[:to] = mail.to
@@ -436,61 +332,16 @@ module ActionMailer #:nodoc:
payload[:mail] = mail.encoded
end
- private
-
- def matches_dynamic_method?(method_name) #:nodoc:
- method_name = method_name.to_s
- /^(create|deliver)_([_a-z]\w*)/.match(method_name) || /^(new)$/.match(method_name)
+ def method_missing(method, *args) #:nodoc:
+ if action_methods.include?(method.to_s)
+ new(method, *args).message
+ else
+ super
end
- end
-
- # Configure delivery method. Check ActionMailer::DeliveryMethod for more
- # instructions.
- superclass_delegating_reader :delivery_method
- self.delivery_method = :smtp
-
- # Add a part to a multipart message, with the given content-type. The
- # part itself is yielded to the block so that other properties (charset,
- # body, headers, etc.) can be set on it.
- def part(params)
- params = {:content_type => params} if String === params
-
- if custom_headers = params.delete(:headers)
- ActiveSupport::Deprecation.warn('Passing custom headers with :headers => {} is deprecated. ' <<
- 'Please just pass in custom headers directly.', caller[0,10])
- params.merge!(custom_headers)
end
-
- part = Mail::Part.new(params)
- yield part if block_given?
- @parts << part
- end
-
- # Add an attachment to a multipart message. This is simply a part with the
- # content-disposition set to "attachment".
- def attachment(params, &block)
- super # Run deprecation hooks
-
- params = { :content_type => params } if String === params
- params = { :content_disposition => "attachment",
- :content_transfer_encoding => "base64" }.merge(params)
-
- part(params, &block)
end
- # Allow you to set assigns for your template:
- #
- # body :greetings => "Hi"
- #
- # Will make @greetings available in the template to be rendered.
- def body(object=nil)
- returning(super) do # Run deprecation hooks
- if object.is_a?(Hash)
- @assigns_set = true
- object.each { |k, v| instance_variable_set(:"@#{k}", v) }
- end
- end
- end
+ attr_internal :message
# Instantiate a new mailer object. If +method_name+ is not +nil+, the mailer
# will be initialized according to the named method. If not, the mailer will
@@ -498,167 +349,263 @@ module ActionMailer #:nodoc:
# method, for instance).
def initialize(method_name=nil, *args)
super()
+ @_message = Mail.new
process(method_name, *args) if method_name
end
- # Process the mailer via the given +method_name+. The body will be
- # rendered and a new Mail object created.
- def process(method_name, *args)
- initialize_defaults(method_name)
- super
-
- # Create e-mail parts
- create_parts
-
- # Set the subject if not set yet
- @subject ||= I18n.t(:subject, :scope => [:actionmailer, mailer_name, method_name],
- :default => method_name.humanize)
-
- # Build the mail object itself
- create_mail
- end
-
- # Delivers a Mail object. By default, it delivers the cached mail
- # object (from the <tt>create!</tt> method). If no cached mail object exists, and
- # no alternate has been given as the parameter, this will fail.
- def deliver!(mail = @mail)
- raise "no mail object available for delivery!" unless mail
-
- ActiveSupport::Notifications.instrument("action_mailer.deliver",
- :template => template, :mailer => self.class.name) do |payload|
-
- self.class.set_payload_for_mail(payload, mail)
-
- begin
- self.delivery_method.perform_delivery(mail) if perform_deliveries
- rescue Exception => e # Net::SMTP errors or sendmail pipe errors
- raise e if raise_delivery_errors
- end
+ # Allows you to pass random and unusual headers to the new +Mail::Message+ object
+ # which will add them to itself.
+ #
+ # headers['X-Special-Domain-Specific-Header'] = "SecretValue"
+ #
+ # You can also pass a hash into headers of header field names and values, which
+ # will then be set on the Mail::Message object:
+ #
+ # headers 'X-Special-Domain-Specific-Header' => "SecretValue",
+ # 'In-Reply-To' => incoming.message_id
+ #
+ # The resulting Mail::Message will have the following in it's header:
+ #
+ # X-Special-Domain-Specific-Header: SecretValue
+ def headers(args=nil)
+ if args
+ @_message.headers(args)
+ else
+ @_message
end
-
- mail
end
- private
+ # Allows you to add attachments to an email, like so:
+ #
+ # mail.attachments['filename.jpg'] = File.read('/path/to/filename.jpg')
+ #
+ # If you do this, then Mail will take the file name and work out the mime type
+ # set the Content-Type, Content-Disposition, Content-Transfer-Encoding and
+ # base64 encode the contents of the attachment all for you.
+ #
+ # You can also specify overrides if you want by passing a hash instead of a string:
+ #
+ # mail.attachments['filename.jpg'] = {:mime_type => 'application/x-gzip',
+ # :content => File.read('/path/to/filename.jpg')}
+ #
+ # If you want to use a different encoding than Base64, you can pass an encoding in,
+ # but then it is up to you to pass in the content pre-encoded, and don't expect
+ # Mail to know how to decode this data:
+ #
+ # file_content = SpecialEncode(File.read('/path/to/filename.jpg'))
+ # mail.attachments['filename.jpg'] = {:mime_type => 'application/x-gzip',
+ # :encoding => 'SpecialEncoding',
+ # :content => file_content }
+ #
+ # You can also search for specific attachments:
+ #
+ # # By Filename
+ # mail.attachments['filename.jpg'] #=> Mail::Part object or nil
+ #
+ # # or by index
+ # mail.attachments[0] #=> Mail::Part (first attachment)
+ #
+ def attachments
+ @_message.attachments
+ end
- # Render a message but does not set it as mail body. Useful for rendering
- # data for part and attachments.
- #
- # Examples:
- #
- # render_message "special_message"
- # render_message :template => "special_message"
- # render_message :inline => "<%= 'Hi!' %>"
- def render_message(object)
- case object
- when String
- render_to_body(:template => object)
- else
- render_to_body(object)
- end
+ # The main method that creates the message and renders the email templates. There are
+ # two ways to call this method, with a block, or without a block.
+ #
+ # Both methods accept a headers hash. This hash allows you to specify the most used headers
+ # in an email message, these are:
+ #
+ # * <tt>:subject</tt> - The subject of the message, if this is omitted, ActionMailer will
+ # ask the Rails I18n class for a translated <tt>:subject</tt> in the scope of
+ # <tt>[:actionmailer, mailer_scope, action_name]</tt> or if this is missing, will translate the
+ # humanized version of the <tt>action_name</tt>
+ # * <tt>:to</tt> - Who the message is destined for, can be a string of addresses, or an array
+ # of addresses.
+ # * <tt>:from</tt> - Who the message is from
+ # * <tt>:cc</tt> - Who you would like to Carbon-Copy on this email, can be a string of addresses,
+ # or an array of addresses.
+ # * <tt>:bcc</tt> - Who you would like to Blind-Carbon-Copy on this email, can be a string of
+ # addresses, or an array of addresses.
+ # * <tt>:reply_to</tt> - Who to set the Reply-To header of the email to.
+ # * <tt>:date</tt> - The date to say the email was sent on.
+ #
+ # You can set default values for any of the above headers (except :date) by using the <tt>default</tt>
+ # class method:
+ #
+ # class Notifier < ActionMailer::Base
+ # self.default :from => 'no-reply@test.lindsaar.net',
+ # :bcc => 'email_logger@test.lindsaar.net',
+ # :reply_to => 'bounces@test.lindsaar.net'
+ # end
+ #
+ # If you need other headers not listed above, use the <tt>headers['name'] = value</tt> method.
+ #
+ # When a <tt>:return_path</tt> is specified as header, that value will be used as the 'envelope from'
+ # address for the Mail message. Setting this is useful when you want delivery notifications
+ # sent to a different address than the one in <tt>:from</tt>. Mail will actually use the
+ # <tt>:return_path</tt> in preference to the <tt>:sender</tt> in preference to the <tt>:from</tt>
+ # field for the 'envelope from' value.
+ #
+ # If you do not pass a block to the +mail+ method, it will find all templates in the
+ # template path that match the method name that it is being called from, it will then
+ # create parts for each of these templates intelligently, making educated guesses
+ # on correct content type and sequence, and return a fully prepared Mail::Message
+ # ready to call <tt>:deliver</tt> on to send.
+ #
+ # If you do pass a block, you can render specific templates of your choice:
+ #
+ # mail(:to => 'mikel@test.lindsaar.net') do |format|
+ # format.text
+ # format.html
+ # end
+ #
+ # You can even render text directly without using a template:
+ #
+ # mail(:to => 'mikel@test.lindsaar.net') do |format|
+ # format.text { render :text => "Hello Mikel!" }
+ # format.html { render :text => "<h1>Hello Mikel!</h1>" }
+ # end
+ #
+ # Which will render a <tt>multipart/alternative</tt> email with <tt>text/plain</tt> and
+ # <tt>text/html</tt> parts.
+ #
+ # The block syntax also allows you to customize the part headers if desired:
+ #
+ # mail(:to => 'mikel@test.lindsaar.net') do |format|
+ # format.text(:content_transfer_encoding => "base64")
+ # format.html
+ # end
+ #
+ def mail(headers={}, &block)
+ # Guard flag to prevent both the old and the new API from firing
+ # Should be removed when old API is removed
+ @mail_was_called = true
+ m = @_message
+
+ # At the beginning, do not consider class default for parts order neither content_type
+ content_type = headers[:content_type]
+ parts_order = headers[:parts_order]
+
+ # Merge defaults from class
+ headers = headers.reverse_merge(self.class.default)
+ charset = headers[:charset]
+
+ # Quote fields
+ headers[:subject] ||= default_i18n_subject
+ quote_fields!(headers, charset)
+
+ # Render the templates and blocks
+ responses, explicit_order = collect_responses_and_parts_order(headers, &block)
+ create_parts_from_responses(m, responses, charset)
+
+ # Finally setup content type and parts order
+ m.content_type = set_content_type(m, content_type, headers[:content_type])
+ m.charset = charset
+
+ if m.multipart?
+ parts_order ||= explicit_order || headers[:parts_order]
+ m.body.set_sort_order(parts_order)
+ m.body.sort_parts!
end
- # Set up the default values for the various instance variables of this
- # mailer. Subclasses may override this method to provide different
- # defaults.
- def initialize_defaults(method_name) #:nodoc:
- @charset ||= @@default_charset.dup
- @content_type ||= @@default_content_type.dup
- @implicit_parts_order ||= @@default_implicit_parts_order.dup
- @mime_version ||= @@default_mime_version.dup if @@default_mime_version
+ # Set configure delivery behavior
+ wrap_delivery_behavior!(headers[:delivery_method])
- @mailer_name ||= self.class.mailer_name.dup
- @template ||= method_name
+ # Remove headers already treated and assign all others
+ headers.except!(:subject, :to, :from, :cc, :bcc, :reply_to)
+ headers.except!(:body, :parts_order, :content_type, :charset, :delivery_method)
+ headers.each { |k, v| m[k] = v }
- @parts ||= []
- @headers ||= {}
- @sent_on ||= Time.now
+ m
+ end
- super # Run deprecation hooks
+ protected
+
+ def set_content_type(m, user_content_type, class_default)
+ params = m.content_type_parameters || {}
+ case
+ when user_content_type.present?
+ user_content_type
+ when m.has_attachments?
+ ["multipart", "mixed", params]
+ when m.multipart?
+ ["multipart", "alternative", params]
+ else
+ m.content_type || class_default
end
+ end
- def create_parts #:nodoc:
- super # Run deprecation hooks
-
- if String === response_body
- @parts.unshift create_inline_part(response_body)
- else
- self.class.template_root.find_all(@template, {}, @mailer_name).each do |template|
- @parts << create_inline_part(render_to_body(:_template => template), template.mime_type)
- end
+ def default_i18n_subject #:nodoc:
+ mailer_scope = self.class.mailer_name.gsub('/', '.')
+ I18n.t(:subject, :scope => [:actionmailer, mailer_scope, action_name], :default => action_name.humanize)
+ end
- if @parts.size > 1
- @content_type = "multipart/alternative" if @content_type !~ /^multipart/
- end
+ # TODO: Move this into Mail
+ def quote_fields!(headers, charset) #:nodoc:
+ m = @_message
+ m.subject ||= quote_if_necessary(headers[:subject], charset) if headers[:subject]
+ m.to ||= quote_address_if_necessary(headers[:to], charset) if headers[:to]
+ m.from ||= quote_address_if_necessary(headers[:from], charset) if headers[:from]
+ m.cc ||= quote_address_if_necessary(headers[:cc], charset) if headers[:cc]
+ m.bcc ||= quote_address_if_necessary(headers[:bcc], charset) if headers[:bcc]
+ m.reply_to ||= quote_address_if_necessary(headers[:reply_to], charset) if headers[:reply_to]
+ end
- # If this is a multipart e-mail add the mime_version if it is not
- # already set.
- @mime_version ||= "1.0" if !@parts.empty?
+ def collect_responses_and_parts_order(headers) #:nodoc:
+ responses, parts_order = [], nil
+
+ if block_given?
+ collector = ActionMailer::Collector.new(self) { render(action_name) }
+ yield(collector)
+ parts_order = collector.responses.map { |r| r[:content_type] }
+ responses = collector.responses
+ elsif headers[:body]
+ responses << {
+ :body => headers[:body],
+ :content_type => self.class.default[:content_type] || "text/plain"
+ }
+ else
+ each_template do |template|
+ responses << {
+ :body => render_to_body(:_template => template),
+ :content_type => template.mime_type.to_s
+ }
end
end
- def create_inline_part(body, mime_type=nil) #:nodoc:
- ct = mime_type || "text/plain"
- main_type, sub_type = split_content_type(ct.to_s)
-
- Mail::Part.new(
- :content_type => [main_type, sub_type, {:charset => charset}],
- :content_disposition => "inline",
- :body => body
- )
- end
-
- def create_mail #:nodoc:
- m = Mail.new
-
- m.subject, = quote_any_if_necessary(charset, subject)
- m.to, m.from = quote_any_address_if_necessary(charset, recipients, from)
- m.bcc = quote_address_if_necessary(bcc, charset) unless bcc.nil?
- m.cc = quote_address_if_necessary(cc, charset) unless cc.nil?
- m.reply_to = quote_address_if_necessary(reply_to, charset) unless reply_to.nil?
- m.mime_version = mime_version unless mime_version.nil?
- m.date = sent_on.to_time rescue sent_on if sent_on
-
- headers.each { |k, v| m[k] = v }
-
- real_content_type, ctype_attrs = parse_content_type
- main_type, sub_type = split_content_type(real_content_type)
-
- if @parts.size == 1 && @parts.first.parts.empty?
- m.content_type([main_type, sub_type, ctype_attrs])
- m.body = @parts.first.body.encoded
- else
- @parts.each do |p|
- m.add_part(p)
- end
+ [responses, parts_order]
+ end
- m.body.set_sort_order(@implicit_parts_order)
- m.body.sort_parts!
+ def each_template(&block) #:nodoc:
+ self.class.view_paths.each do |load_paths|
+ templates = load_paths.find_all(action_name, {}, self.class.mailer_name)
+ templates = templates.uniq_by { |t| t.details[:formats] }
- if real_content_type =~ /multipart/
- ctype_attrs.delete "charset"
- m.content_type([main_type, sub_type, ctype_attrs])
- end
+ unless templates.empty?
+ templates.each(&block)
+ return
end
-
- m.content_transfer_encoding = '8bit' unless m.body.only_us_ascii?
-
- @mail = m
- end
-
- def split_content_type(ct) #:nodoc:
- ct.to_s.split("/")
end
+ end
- def parse_content_type(defaults=nil) #:nodoc:
- if @content_type.blank?
- [ nil, {} ]
- else
- ctype, *attrs = @content_type.split(/;\s*/)
- attrs = attrs.inject({}) { |h,s| k,v = s.split(/\=/, 2); h[k] = v; h }
- [ctype, {"charset" => @charset}.merge(attrs)]
- end
+ def create_parts_from_responses(m, responses, charset) #:nodoc:
+ if responses.size == 1 && !m.has_attachments?
+ responses[0].each { |k,v| m[k] = v }
+ elsif responses.size > 1 && m.has_attachments?
+ container = Mail::Part.new
+ container.content_type = "multipart/alternative"
+ responses.each { |r| insert_part(container, r, charset) }
+ m.add_part(container)
+ else
+ responses.each { |r| insert_part(m, r, charset) }
end
+ end
+
+ def insert_part(container, response, charset) #:nodoc:
+ response[:charset] ||= charset
+ part = Mail::Part.new(response)
+ container.add_part(part)
+ end
end
end
diff --git a/actionmailer/lib/action_mailer/collector.rb b/actionmailer/lib/action_mailer/collector.rb
new file mode 100644
index 0000000000..5431efccfe
--- /dev/null
+++ b/actionmailer/lib/action_mailer/collector.rb
@@ -0,0 +1,36 @@
+require 'abstract_controller/collector'
+require 'active_support/core_ext/hash/reverse_merge'
+require 'active_support/core_ext/array/extract_options'
+
+module ActionMailer #:nodoc:
+ class Collector
+ include AbstractController::Collector
+ attr_reader :responses
+
+ def initialize(context, &block)
+ @context = context
+ @responses = []
+ @default_render = block
+ @default_formats = context.formats
+ end
+
+ def any(*args, &block)
+ options = args.extract_options!
+ raise "You have to supply at least one format" if args.empty?
+ args.each { |type| send(type, options.dup, &block) }
+ end
+ alias :all :any
+
+ def custom(mime, options={}, &block)
+ options.reverse_merge!(:content_type => mime.to_s)
+ @context.formats = [mime.to_sym]
+ options[:body] = if block
+ block.call
+ else
+ @default_render.call
+ end
+ @responses << options
+ @context.formats = @default_formats
+ end
+ end
+end \ No newline at end of file
diff --git a/actionmailer/lib/action_mailer/delivery_method.rb b/actionmailer/lib/action_mailer/delivery_method.rb
deleted file mode 100644
index 4f7d3afc3c..0000000000
--- a/actionmailer/lib/action_mailer/delivery_method.rb
+++ /dev/null
@@ -1,56 +0,0 @@
-require 'active_support/core_ext/class'
-
-module ActionMailer
- module DeliveryMethod
- autoload :File, 'action_mailer/delivery_method/file'
- autoload :Sendmail, 'action_mailer/delivery_method/sendmail'
- autoload :Smtp, 'action_mailer/delivery_method/smtp'
- autoload :Test, 'action_mailer/delivery_method/test'
-
- # Creates a new DeliveryMethod object according to the given options.
- #
- # If no arguments are passed to this method, then a new
- # ActionMailer::DeliveryMethod::Stmp object will be returned.
- #
- # If you pass a Symbol as the first argument, then a corresponding
- # delivery method class under the ActionMailer::DeliveryMethod namespace
- # will be created.
- # For example:
- #
- # ActionMailer::DeliveryMethod.lookup_method(:sendmail)
- # # => returns a new ActionMailer::DeliveryMethod::Sendmail object
- #
- # If the first argument is not a Symbol, then it will simply be returned:
- #
- # ActionMailer::DeliveryMethod.lookup_method(MyOwnDeliveryMethod.new)
- # # => returns MyOwnDeliveryMethod.new
- def self.lookup_method(delivery_method)
- case delivery_method
- when Symbol
- method_name = delivery_method.to_s.camelize
- method_class = ActionMailer::DeliveryMethod.const_get(method_name)
- method_class.new
- when nil # default
- Smtp.new
- else
- delivery_method
- end
- end
-
- # An abstract delivery method class. There are multiple delivery method classes.
- # See the classes under the ActionMailer::DeliveryMethod, e.g.
- # ActionMailer::DeliveryMethod::Smtp.
- # Smtp is the default delivery method for production
- # while Test is used in testing.
- #
- # each delivery method exposes just one method
- #
- # delivery_method = ActionMailer::DeliveryMethod::Smtp.new
- # delivery_method.perform_delivery(mail) # send the mail via smtp
- #
- class Method
- superclass_delegating_accessor :settings
- self.settings = {}
- end
- end
-end
diff --git a/actionmailer/lib/action_mailer/delivery_method/file.rb b/actionmailer/lib/action_mailer/delivery_method/file.rb
deleted file mode 100644
index 571e32df49..0000000000
--- a/actionmailer/lib/action_mailer/delivery_method/file.rb
+++ /dev/null
@@ -1,21 +0,0 @@
-require 'tmpdir'
-
-module ActionMailer
- module DeliveryMethod
-
- # A delivery method implementation which writes all mails to a file.
- class File < Method
- self.settings = {
- :location => defined?(Rails.root) ? "#{Rails.root}/tmp/mails" : "#{Dir.tmpdir}/mails"
- }
-
- def perform_delivery(mail)
- FileUtils.mkdir_p settings[:location]
-
- mail.destinations.uniq.each do |to|
- ::File.open(::File.join(settings[:location], to), 'a') { |f| f.write(mail) }
- end
- end
- end
- end
-end
diff --git a/actionmailer/lib/action_mailer/delivery_method/sendmail.rb b/actionmailer/lib/action_mailer/delivery_method/sendmail.rb
deleted file mode 100644
index db55af79f1..0000000000
--- a/actionmailer/lib/action_mailer/delivery_method/sendmail.rb
+++ /dev/null
@@ -1,22 +0,0 @@
-module ActionMailer
- module DeliveryMethod
-
- # A delivery method implementation which sends via sendmail.
- class Sendmail < Method
- self.settings = {
- :location => '/usr/sbin/sendmail',
- :arguments => '-i -t'
- }
-
- def perform_delivery(mail)
- sendmail_args = settings[:arguments]
- sendmail_args += " -f \"#{mail['return-path']}\"" if mail['return-path']
- IO.popen("#{settings[:location]} #{sendmail_args}","w+") do |sm|
- sm.print(mail.encoded.gsub(/\r/, ''))
- sm.flush
- end
- end
- end
-
- end
-end
diff --git a/actionmailer/lib/action_mailer/delivery_method/smtp.rb b/actionmailer/lib/action_mailer/delivery_method/smtp.rb
deleted file mode 100644
index af30c498b5..0000000000
--- a/actionmailer/lib/action_mailer/delivery_method/smtp.rb
+++ /dev/null
@@ -1,30 +0,0 @@
-require 'net/smtp'
-
-module ActionMailer
- module DeliveryMethod
- # A delivery method implementation which sends via smtp.
- class Smtp < Method
- self.settings = {
- :address => "localhost",
- :port => 25,
- :domain => 'localhost.localdomain',
- :user_name => nil,
- :password => nil,
- :authentication => nil,
- :enable_starttls_auto => true,
- }
-
- def perform_delivery(mail)
- destinations = mail.destinations
- sender = (mail['return-path'] && mail['return-path'].address) || mail['from']
-
- smtp = Net::SMTP.new(settings[:address], settings[:port])
- smtp.enable_starttls_auto if settings[:enable_starttls_auto] && smtp.respond_to?(:enable_starttls_auto)
- smtp.start(settings[:domain], settings[:user_name], settings[:password],
- settings[:authentication]) do |smtp|
- smtp.sendmail(mail.encoded, sender, destinations)
- end
- end
- end
- end
-end
diff --git a/actionmailer/lib/action_mailer/delivery_method/test.rb b/actionmailer/lib/action_mailer/delivery_method/test.rb
deleted file mode 100644
index 6e3239d52a..0000000000
--- a/actionmailer/lib/action_mailer/delivery_method/test.rb
+++ /dev/null
@@ -1,12 +0,0 @@
-module ActionMailer
- module DeliveryMethod
-
- # A delivery method implementation designed for testing, which just appends each record to the :deliveries array
- class Test < Method
- def perform_delivery(mail)
- ActionMailer::Base.deliveries << mail
- end
- end
-
- end
-end
diff --git a/actionmailer/lib/action_mailer/delivery_methods.rb b/actionmailer/lib/action_mailer/delivery_methods.rb
new file mode 100644
index 0000000000..f6321a240c
--- /dev/null
+++ b/actionmailer/lib/action_mailer/delivery_methods.rb
@@ -0,0 +1,90 @@
+require 'tmpdir'
+
+module ActionMailer
+ # This modules handles everything related to the delivery, from registering new
+ # delivery methods to configuring the mail object to be send.
+ module DeliveryMethods
+ extend ActiveSupport::Concern
+
+ included do
+ extlib_inheritable_accessor :delivery_methods, :delivery_method,
+ :instance_writer => false
+
+ # Do not make this inheritable, because we always want it to propagate
+ cattr_accessor :raise_delivery_errors
+ self.raise_delivery_errors = true
+
+ cattr_accessor :perform_deliveries
+ self.perform_deliveries = true
+
+ self.delivery_methods = {}
+ self.delivery_method = :smtp
+
+ add_delivery_method :smtp, Mail::SMTP,
+ :address => "localhost",
+ :port => 25,
+ :domain => 'localhost.localdomain',
+ :user_name => nil,
+ :password => nil,
+ :authentication => nil,
+ :enable_starttls_auto => true
+
+ add_delivery_method :file, Mail::FileDelivery,
+ :location => defined?(Rails.root) ? "#{Rails.root}/tmp/mails" : "#{Dir.tmpdir}/mails"
+
+ add_delivery_method :sendmail, Mail::Sendmail,
+ :location => '/usr/sbin/sendmail',
+ :arguments => '-i -t'
+
+ add_delivery_method :test, Mail::TestMailer
+ end
+
+ module ClassMethods
+ # Provides a list of emails that have been delivered by Mail::TestMailer
+ delegate :deliveries, :deliveries=, :to => Mail::TestMailer
+
+ # Adds a new delivery method through the given class using the given symbol
+ # as alias and the default options supplied:
+ #
+ # Example:
+ #
+ # add_delivery_method :sendmail, Mail::Sendmail,
+ # :location => '/usr/sbin/sendmail',
+ # :arguments => '-i -t'
+ #
+ def add_delivery_method(symbol, klass, default_options={})
+ unless respond_to?(:"#{symbol}_settings")
+ extlib_inheritable_accessor(:"#{symbol}_settings", :instance_writer => false)
+ end
+
+ send(:"#{symbol}_settings=", default_options)
+ self.delivery_methods[symbol.to_sym] = klass
+ end
+
+ def wrap_delivery_behavior(mail, method=nil) #:nodoc:
+ method ||= self.delivery_method
+ mail.delivery_handler = self
+
+ case method
+ when NilClass
+ raise "Delivery method cannot be nil"
+ when Symbol
+ if klass = delivery_methods[method.to_sym]
+ mail.delivery_method(klass, send(:"#{method}_settings"))
+ else
+ raise "Invalid delivery method #{method.inspect}"
+ end
+ else
+ mail.delivery_method(method)
+ end
+
+ mail.perform_deliveries = perform_deliveries
+ mail.raise_delivery_errors = raise_delivery_errors
+ end
+ end
+
+ def wrap_delivery_behavior!(*args) #:nodoc:
+ self.class.wrap_delivery_behavior(message, *args)
+ end
+ end
+end \ No newline at end of file
diff --git a/actionmailer/lib/action_mailer/deprecated_api.rb b/actionmailer/lib/action_mailer/deprecated_api.rb
new file mode 100644
index 0000000000..54ad18f796
--- /dev/null
+++ b/actionmailer/lib/action_mailer/deprecated_api.rb
@@ -0,0 +1,139 @@
+module ActionMailer
+ # This is the API which is deprecated and is going to be removed on Rails 3.1 release.
+ # Part of the old API will be deprecated after 3.1, for a smoother deprecation process.
+ # Chech those in OldApi instead.
+ module DeprecatedApi #:nodoc:
+ extend ActiveSupport::Concern
+
+ included do
+ [:charset, :content_type, :mime_version, :implicit_parts_order].each do |method|
+ class_eval <<-FILE, __FILE__, __LINE__ + 1
+ def self.default_#{method}
+ @@default_#{method}
+ end
+
+ def self.default_#{method}=(value)
+ ActiveSupport::Deprecation.warn "ActionMailer::Base.default_#{method}=value is deprecated, " <<
+ "use default :#{method} => value instead"
+ @@default_#{method} = value
+ end
+
+ @@default_#{method} = nil
+ FILE
+ end
+ end
+
+ module ClassMethods
+ # Deliver the given mail object directly. This can be used to deliver
+ # a preconstructed mail object, like:
+ #
+ # email = MyMailer.create_some_mail(parameters)
+ # email.set_some_obscure_header "frobnicate"
+ # MyMailer.deliver(email)
+ def deliver(mail, show_warning=true)
+ if show_warning
+ ActiveSupport::Deprecation.warn "#{self}.deliver is deprecated, call " <<
+ "deliver in the mailer instance instead", caller[0,2]
+ end
+
+ raise "no mail object available for delivery!" unless mail
+ wrap_delivery_behavior(mail)
+ mail.deliver
+ mail
+ end
+
+ def template_root
+ self.view_paths && self.view_paths.first
+ end
+
+ def template_root=(root)
+ ActiveSupport::Deprecation.warn "template_root= is deprecated, use view_paths.unshift instead", caller[0,2]
+ self.view_paths = ActionView::Base.process_view_paths(root)
+ end
+
+ def respond_to?(method_symbol, include_private = false)
+ matches_dynamic_method?(method_symbol) || super
+ end
+
+ def method_missing(method_symbol, *parameters)
+ if match = matches_dynamic_method?(method_symbol)
+ case match[1]
+ when 'create'
+ ActiveSupport::Deprecation.warn "#{self}.create_#{match[2]} is deprecated, " <<
+ "use #{self}.#{match[2]} instead", caller[0,2]
+ new(match[2], *parameters).message
+ when 'deliver'
+ ActiveSupport::Deprecation.warn "#{self}.deliver_#{match[2]} is deprecated, " <<
+ "use #{self}.#{match[2]}.deliver instead", caller[0,2]
+ new(match[2], *parameters).message.deliver
+ else super
+ end
+ else
+ super
+ end
+ end
+
+ private
+
+ def matches_dynamic_method?(method_name)
+ method_name = method_name.to_s
+ /^(create|deliver)_([_a-z]\w*)/.match(method_name) || /^(new)$/.match(method_name)
+ end
+ end
+
+ # Delivers a Mail object. By default, it delivers the cached mail
+ # object (from the <tt>create!</tt> method). If no cached mail object exists, and
+ # no alternate has been given as the parameter, this will fail.
+ def deliver!(mail = @_message)
+ ActiveSupport::Deprecation.warn "Calling deliver in the AM::Base object is deprecated, " <<
+ "please call deliver in the Mail instance", caller[0,2]
+ self.class.deliver(mail, false)
+ end
+ alias :deliver :deliver!
+
+ def render(*args)
+ options = args.last.is_a?(Hash) ? args.last : {}
+
+ if options[:body].is_a?(Hash)
+ ActiveSupport::Deprecation.warn(':body in render deprecated. Please use instance ' <<
+ 'variables as assigns instead', caller[0,1])
+
+ options[:body].each { |k,v| instance_variable_set(:"@#{k}", v) }
+ end
+ super
+ end
+
+ # Render a message but does not set it as mail body. Useful for rendering
+ # data for part and attachments.
+ #
+ # Examples:
+ #
+ # render_message "special_message"
+ # render_message :template => "special_message"
+ # render_message :inline => "<%= 'Hi!' %>"
+ #
+ def render_message(*args)
+ ActiveSupport::Deprecation.warn "render_message is deprecated, use render instead", caller[0,2]
+ render(*args)
+ end
+
+ private
+
+ def initialize_defaults(*)
+ @charset ||= self.class.default_charset.try(:dup)
+ @content_type ||= self.class.default_content_type.try(:dup)
+ @implicit_parts_order ||= self.class.default_implicit_parts_order.try(:dup)
+ @mime_version ||= self.class.default_mime_version.try(:dup)
+ super
+ end
+
+ def create_parts
+ if @body.is_a?(Hash) && !@body.empty?
+ ActiveSupport::Deprecation.warn "Giving a hash to body is deprecated, please use instance variables instead", caller[0,2]
+ @body.each { |k, v| instance_variable_set(:"@#{k}", v) }
+ end
+ super
+ end
+
+ end
+end
diff --git a/actionmailer/lib/action_mailer/deprecated_body.rb b/actionmailer/lib/action_mailer/deprecated_body.rb
deleted file mode 100644
index 5379b33a54..0000000000
--- a/actionmailer/lib/action_mailer/deprecated_body.rb
+++ /dev/null
@@ -1,46 +0,0 @@
-module ActionMailer
- # TODO Remove this module all together in a next release. Ensure that super
- # hooks and @assigns_set in ActionMailer::Base are removed as well.
- module DeprecatedBody
- extend ActionMailer::AdvAttrAccessor
-
- # Define the body of the message. This is either a Hash (in which case it
- # specifies the variables to pass to the template when it is rendered),
- # or a string, in which case it specifies the actual text of the message.
- adv_attr_accessor :body
-
- def initialize_defaults(method_name)
- @body ||= {}
- end
-
- def attachment(params, &block)
- if params[:body]
- ActiveSupport::Deprecation.warn('attachment :body => "string" is deprecated. To set the body of an attachment ' <<
- 'please use :data instead, like attachment :data => "string"', caller[0,10])
- params[:data] = params.delete(:body)
- end
- end
-
- def create_parts
- if String === @body && !defined?(@assigns_set)
- ActiveSupport::Deprecation.warn('body(String) is deprecated. To set the body with a text ' <<
- 'call render(:text => "body")', caller[0,10])
- self.response_body = @body
- elsif self.response_body
- @body = self.response_body
- end
- end
-
- def render(*args)
- options = args.last.is_a?(Hash) ? args.last : {}
- if options[:body]
- ActiveSupport::Deprecation.warn(':body in render deprecated. Please call body ' <<
- 'with a hash instead', caller[0,1])
-
- body options.delete(:body)
- end
-
- super
- end
- end
-end
diff --git a/actionmailer/lib/action_mailer/mail_helper.rb b/actionmailer/lib/action_mailer/mail_helper.rb
index 701dc34431..ab5c3469b2 100644
--- a/actionmailer/lib/action_mailer/mail_helper.rb
+++ b/actionmailer/lib/action_mailer/mail_helper.rb
@@ -17,8 +17,13 @@ module ActionMailer
end
# Access the mailer instance.
- def mailer #:nodoc:
- @controller
+ def mailer
+ @_controller
+ end
+
+ # Access the message instance.
+ def message
+ @_message
end
end
end
diff --git a/actionmailer/lib/action_mailer/old_api.rb b/actionmailer/lib/action_mailer/old_api.rb
new file mode 100644
index 0000000000..936ceb0dd6
--- /dev/null
+++ b/actionmailer/lib/action_mailer/old_api.rb
@@ -0,0 +1,248 @@
+require 'active_support/core_ext/object/try'
+
+module ActionMailer
+ module OldApi #:nodoc:
+ extend ActiveSupport::Concern
+
+ included do
+ extend ActionMailer::AdvAttrAccessor
+
+ @@protected_instance_variables = %w(@parts)
+ cattr_reader :protected_instance_variables
+
+ # Specify the BCC addresses for the message
+ adv_attr_accessor :bcc
+
+ # Specify the CC addresses for the message.
+ adv_attr_accessor :cc
+
+ # Specify the charset to use for the message. This defaults to the
+ # +default_charset+ specified for ActionMailer::Base.
+ adv_attr_accessor :charset
+
+ # Specify the content type for the message. This defaults to <tt>text/plain</tt>
+ # in most cases, but can be automatically set in some situations.
+ adv_attr_accessor :content_type
+
+ # Specify the from address for the message.
+ adv_attr_accessor :from
+
+ # Specify the address (if different than the "from" address) to direct
+ # replies to this message.
+ adv_attr_accessor :reply_to
+
+ # Specify additional headers to be added to the message.
+ adv_attr_accessor :headers
+
+ # Specify the order in which parts should be sorted, based on content-type.
+ # This defaults to the value for the +default_implicit_parts_order+.
+ adv_attr_accessor :implicit_parts_order
+
+ # Defaults to "1.0", but may be explicitly given if needed.
+ adv_attr_accessor :mime_version
+
+ # The recipient addresses for the message, either as a string (for a single
+ # address) or an array (for multiple addresses).
+ adv_attr_accessor :recipients
+
+ # The date on which the message was sent. If not set (the default), the
+ # header will be set by the delivery agent.
+ adv_attr_accessor :sent_on
+
+ # Specify the subject of the message.
+ adv_attr_accessor :subject
+
+ # Specify the template name to use for current message. This is the "base"
+ # template name, without the extension or directory, and may be used to
+ # have multiple mailer methods share the same template.
+ adv_attr_accessor :template
+
+ # Override the mailer name, which defaults to an inflected version of the
+ # mailer's class name. If you want to use a template in a non-standard
+ # location, you can use this to specify that location.
+ adv_attr_accessor :mailer_name
+
+ # Define the body of the message. This is either a Hash (in which case it
+ # specifies the variables to pass to the template when it is rendered),
+ # or a string, in which case it specifies the actual text of the message.
+ adv_attr_accessor :body
+
+ # Alias controller_path to mailer_name so render :partial in views work.
+ alias :controller_path :mailer_name
+ end
+
+ def process(method_name, *args)
+ initialize_defaults(method_name)
+ super
+ unless @mail_was_called
+ create_parts
+ create_mail
+ end
+ @_message
+ end
+
+ # Add a part to a multipart message, with the given content-type. The
+ # part itself is yielded to the block so that other properties (charset,
+ # body, headers, etc.) can be set on it.
+ def part(params)
+ params = {:content_type => params} if String === params
+
+ if custom_headers = params.delete(:headers)
+ params.merge!(custom_headers)
+ end
+
+ part = Mail::Part.new(params)
+
+ yield part if block_given?
+ @parts << part
+ end
+
+ # Add an attachment to a multipart message. This is simply a part with the
+ # content-disposition set to "attachment".
+ def attachment(params, &block)
+ params = { :content_type => params } if String === params
+
+ params[:content] ||= params.delete(:data) || params.delete(:body)
+
+ if params[:filename]
+ params = normalize_file_hash(params)
+ else
+ params = normalize_nonfile_hash(params)
+ end
+
+ part(params, &block)
+ end
+
+ protected
+
+ def normalize_nonfile_hash(params)
+ content_disposition = "attachment;"
+
+ mime_type = params.delete(:mime_type)
+
+ if content_type = params.delete(:content_type)
+ content_type = "#{mime_type || content_type};"
+ end
+
+ params[:body] = params.delete(:data) if params[:data]
+
+ { :content_type => content_type,
+ :content_disposition => content_disposition }.merge(params)
+ end
+
+ def normalize_file_hash(params)
+ filename = File.basename(params.delete(:filename))
+ content_disposition = "attachment; filename=\"#{File.basename(filename)}\""
+
+ mime_type = params.delete(:mime_type)
+
+ if (content_type = params.delete(:content_type)) && (content_type !~ /filename=/)
+ content_type = "#{mime_type || content_type}; filename=\"#{filename}\""
+ end
+
+ params[:body] = params.delete(:data) if params[:data]
+
+ { :content_type => content_type,
+ :content_disposition => content_disposition }.merge(params)
+ end
+
+ def create_mail
+ m = @_message
+
+ quote_fields!({:subject => subject, :to => recipients, :from => from,
+ :bcc => bcc, :cc => cc, :reply_to => reply_to}, charset)
+
+ m.mime_version = mime_version unless mime_version.nil?
+ m.date = sent_on.to_time rescue sent_on if sent_on
+
+ @headers.each { |k, v| m[k] = v }
+
+ real_content_type, ctype_attrs = parse_content_type
+ main_type, sub_type = split_content_type(real_content_type)
+
+ if @parts.size == 1 && @parts.first.parts.empty?
+ m.content_type([main_type, sub_type, ctype_attrs])
+ m.body = @parts.first.body.encoded
+ else
+ @parts.each do |p|
+ m.add_part(p)
+ end
+
+ m.body.set_sort_order(@implicit_parts_order)
+ m.body.sort_parts!
+
+ if real_content_type =~ /multipart/
+ ctype_attrs.delete "charset"
+ m.content_type([main_type, sub_type, ctype_attrs])
+ end
+ end
+
+ wrap_delivery_behavior!
+ m.content_transfer_encoding = '8bit' unless m.body.only_us_ascii?
+
+ @_message
+ end
+
+ # Set up the default values for the various instance variables of this
+ # mailer. Subclasses may override this method to provide different
+ # defaults.
+ def initialize_defaults(method_name)
+ @charset ||= self.class.default[:charset].try(:dup)
+ @content_type ||= self.class.default[:content_type].try(:dup)
+ @implicit_parts_order ||= self.class.default[:parts_order].try(:dup)
+ @mime_version ||= self.class.default[:mime_version].try(:dup)
+
+ @mailer_name ||= self.class.mailer_name.dup
+ @template ||= method_name
+ @mail_was_called = false
+
+ @parts ||= []
+ @headers ||= {}
+ @sent_on ||= Time.now
+ @body ||= {}
+ end
+
+ def create_parts
+ if String === @body
+ @parts.unshift create_inline_part(@body)
+ elsif @parts.empty? || @parts.all? { |p| p.content_disposition =~ /^attachment/ }
+ self.class.view_paths.first.find_all(@template, {}, @mailer_name).each do |template|
+ @parts << create_inline_part(render_to_body(:_template => template), template.mime_type)
+ end
+
+ if @parts.size > 1
+ @content_type = "multipart/alternative" if @content_type !~ /^multipart/
+ end
+
+ # If this is a multipart e-mail add the mime_version if it is not
+ # already set.
+ @mime_version ||= "1.0" if !@parts.empty?
+ end
+ end
+
+ def create_inline_part(body, mime_type=nil)
+ ct = mime_type || "text/plain"
+ main_type, sub_type = split_content_type(ct.to_s)
+
+ Mail::Part.new(
+ :content_type => [main_type, sub_type, {:charset => charset}],
+ :content_disposition => "inline",
+ :body => body
+ )
+ end
+
+ def split_content_type(ct)
+ ct.to_s.split("/")
+ end
+
+ def parse_content_type(defaults=nil)
+ if @content_type.blank?
+ [ nil, {} ]
+ else
+ ctype, *attrs = @content_type.split(/;\s*/)
+ attrs = attrs.inject({}) { |h,s| k,v = s.split(/\=/, 2); h[k] = v; h }
+ [ctype, {"charset" => @charset}.merge(attrs)]
+ end
+ end
+ end
+end
diff --git a/actionmailer/lib/action_mailer/railtie.rb b/actionmailer/lib/action_mailer/railtie.rb
index b05d21ae5d..7ed1519e36 100644
--- a/actionmailer/lib/action_mailer/railtie.rb
+++ b/actionmailer/lib/action_mailer/railtie.rb
@@ -3,26 +3,19 @@ require "rails"
module ActionMailer
class Railtie < Rails::Railtie
- plugin_name :action_mailer
+ railtie_name :action_mailer
require "action_mailer/railties/subscriber"
subscriber ActionMailer::Railties::Subscriber.new
- initializer "action_mailer.set_configs" do |app|
- app.config.action_mailer.each do |k,v|
- ActionMailer::Base.send "#{k}=", v
- end
- end
-
- # TODO: ActionController::Base.logger should delegate to its own config.logger
initializer "action_mailer.logger" do
ActionMailer::Base.logger ||= Rails.logger
end
- initializer "action_mailer.view_paths" do |app|
- # TODO: this should be combined with the logic for default config.action_mailer.view_paths
- view_path = ActionView::PathSet.type_cast(app.config.view_path, app.config.cache_classes)
- ActionMailer::Base.template_root = view_path if ActionMailer::Base.view_paths.blank?
+ initializer "action_mailer.set_configs" do |app|
+ app.config.action_mailer.each do |k,v|
+ ActionMailer::Base.send "#{k}=", v
+ end
end
end
end \ No newline at end of file
diff --git a/actionmailer/lib/action_mailer/test_case.rb b/actionmailer/lib/action_mailer/test_case.rb
index 0ca4f5494e..7c4033a125 100644
--- a/actionmailer/lib/action_mailer/test_case.rb
+++ b/actionmailer/lib/action_mailer/test_case.rb
@@ -37,7 +37,7 @@ module ActionMailer
def initialize_test_deliveries
ActionMailer::Base.delivery_method = :test
ActionMailer::Base.perform_deliveries = true
- ActionMailer::Base.deliveries = []
+ ActionMailer::Base.deliveries.clear
end
def set_expected_mail
diff --git a/actionmailer/lib/action_mailer/test_helper.rb b/actionmailer/lib/action_mailer/test_helper.rb
index f234c0248c..3a1612442f 100644
--- a/actionmailer/lib/action_mailer/test_helper.rb
+++ b/actionmailer/lib/action_mailer/test_helper.rb
@@ -58,7 +58,6 @@ module ActionMailer
end
end
-# TODO: Deprecate this
module Test
module Unit
class TestCase
diff --git a/actionmailer/lib/action_mailer/tmail_compat.rb b/actionmailer/lib/action_mailer/tmail_compat.rb
index 2fd25ff145..c6efdc53b6 100644
--- a/actionmailer/lib/action_mailer/tmail_compat.rb
+++ b/actionmailer/lib/action_mailer/tmail_compat.rb
@@ -2,19 +2,27 @@ module Mail
class Message
def set_content_type(*args)
- STDERR.puts("Message#set_content_type is deprecated, please just call Message#content_type with the same arguments.\n#{caller}")
+ ActiveSupport::Deprecation.warn('Message#set_content_type is deprecated, please just call ' <<
+ 'Message#content_type with the same arguments', caller[0,2])
content_type(*args)
end
alias :old_transfer_encoding :transfer_encoding
def transfer_encoding(value = nil)
if value
- STDERR.puts("Message#transfer_encoding is deprecated, please call Message#content_transfer_encoding with the same arguments.\n#{caller}")
+ ActiveSupport::Deprecation.warn('Message#transfer_encoding is deprecated, please call ' <<
+ 'Message#content_transfer_encoding with the same arguments', caller[0,2])
content_transfer_encoding(value)
else
old_transfer_encoding
end
end
+ def original_filename
+ ActiveSupport::Deprecation.warn('Message#original_filename is deprecated, ' <<
+ 'please call Message#filename', caller[0,2])
+ filename
+ end
+
end
end \ No newline at end of file
diff --git a/actionmailer/lib/action_mailer/vendor/text-format-0.6.3/text/format.rb b/actionmailer/lib/action_mailer/vendor/text-format-0.6.3/text/format.rb
deleted file mode 100755
index 81cc7906d8..0000000000
--- a/actionmailer/lib/action_mailer/vendor/text-format-0.6.3/text/format.rb
+++ /dev/null
@@ -1,1467 +0,0 @@
-#--
-# 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:
- # Text::Format for Ruby is copyright 2002 - 2005 by Austin Ziegler. It
- # is available under Ruby's licence, the Perl Artistic licence, or the
- # GNU GPL version 2 (or at your option, any later version). As a
- # special exception, for use with official Rails (provided by the
- # rubyonrails.org development team) and any project created with
- # official Rails, the following alternative MIT-style licence may be
- # used:
- #
- # == Text::Format Licence for Rails and Rails Applications
- # 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 names of its contributors may not be used to endorse or
- # promote products derived from this software without specific prior
- # written permission.
- #
- # 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.
- 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)
- @text = nil
- 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_raise(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/text_format.rb b/actionmailer/lib/action_mailer/vendor/text_format.rb
deleted file mode 100644
index c6c8c394d0..0000000000
--- a/actionmailer/lib/action_mailer/vendor/text_format.rb
+++ /dev/null
@@ -1,10 +0,0 @@
-# Prefer gems to the bundled libs.
-require 'rubygems'
-
-begin
- gem 'text-format', '>= 0.6.3'
-rescue Gem::LoadError
- $:.unshift "#{File.dirname(__FILE__)}/text-format-0.6.3"
-end
-
-require 'text/format'