lib/roda/plugins/mailer.rb in roda-2.2.0 vs lib/roda/plugins/mailer.rb in roda-2.3.0

- old
+ new

@@ -85,10 +85,18 @@ # to 'to@example.com' # subject 'No Body Here' # "" # end # + # If while preparing the email you figure out you don't want to send an + # email, call +no_mail!+: + # + # r.mail '/welcome/:d' do |id| + # no_mail! unless user = User[id] + # # ... + # end + # # By default, the mailer uses text/plain as the Content-Type for emails. # You can override the default by specifying a :content_type option when # loading the plugin: # # plugin :mailer, :content_type=>'text/html' @@ -126,19 +134,23 @@ # Return a Mail::Message instance for the email for the given request path # and arguments. You can further manipulate the returned mail object before # calling +deliver+ to send the mail. def mail(path, *args) mail = ::Mail.new - unless mail.equal?(new(PATH_INFO=>path, SCRIPT_NAME=>EMPTY_STRING, REQUEST_METHOD=>MAIL, RACK_INPUT=>StringIO.new, RODA_MAIL=>mail, RODA_MAIL_ARGS=>args).call(&route_block)) - raise Error, "route did not return mail instance for #{path.inspect}, #{args.inspect}" + catch(:no_mail) do + unless mail.equal?(new(PATH_INFO=>path, SCRIPT_NAME=>EMPTY_STRING, REQUEST_METHOD=>MAIL, RACK_INPUT=>StringIO.new, RODA_MAIL=>mail, RODA_MAIL_ARGS=>args).call(&route_block)) + raise Error, "route did not return mail instance for #{path.inspect}, #{args.inspect}" + end + mail end - mail end # Calls +mail+ and immediately sends the resulting mail. def sendmail(*args) - mail(*args).deliver + if m = mail(*args) + m.deliver + end end end module RequestMethods # Similar to routing tree methods such as +get+ and +post+, this matches @@ -147,11 +159,11 @@ # the request. This yields any of the captures to the block, as well as # any arguments passed to the +mail+ or +sendmail+ Roda class methods. def mail(*args) if @env[REQUEST_METHOD] == MAIL if_match(args) do |*vs| - yield *(vs + @env[RODA_MAIL_ARGS]) + yield(*(vs + @env[RODA_MAIL_ARGS])) end end end end @@ -228,9 +240,14 @@ # If a block is given, the block is called after the file has been added, and you # can access the attachment via <tt>response.mail.attachments.last</tt>. def add_file(*a, &block) response.mail_attachments << [a, block] nil + end + + # Signal that no mail should be sent for this request. + def no_mail! + throw :no_mail end private # Set the text_part or html_part (depending on the method) in the related email,