AndreDurao
AndreDurao

Reputation: 5795

Why can't I have a mailer method named message?

I've created a new mail on rails 5 using the mailer generator:

$ rails g mailer mymailer message

Rails created the application_mailer, mymailer_mailer, views and tests. Ok.

This is the mailer generated by rails:

class MymailerMailer < ApplicationMailer

  # Subject can be set in your I18n file at config/locales/en.yml
  # with the following lookup:
  #
  #   en.mymailer_mailer.message.subject
  #
  def message
    @greeting = "Hi"

    mail to: "[email protected]"
  end
end

But whenever I've tried to send the mail I've got the following error:

NoMethodError: undefined method `reject!' for nil:NilClass

After spent about two hours double-checking every config file I've decided to change method to bla...

Voilà: It worked, Ok! But why?

BTW: The message method I've found is from ActionMailer::MessageDelivery but there's no mention on Rails Guides of that.

Upvotes: 0

Views: 65

Answers (2)

Robin Daugherty
Robin Daugherty

Reputation: 7524

As another answer stated, there's already a method in the class named message. This shouldn't be a problem if you use the class as intended, since the mailer shouldn't have a single message named "message", it should have a more descriptive name.

The intent of a Mailer object is to define a context for messages that may be sent.

So for example, a UserMailer would be used to build messages to a user. Then each different type of message has a method, such as forgotten_password or welcome.

The documentation includes a more thorough example that follows this.

Upvotes: 0

Matt Clark
Matt Clark

Reputation: 28589

If you look at the docs for MessageDelivery, there appears to be a method already provided named message which

Returns the resulting Mail::Message

My assumption is that your definition is overriding this provided method, but you are not returning the expected Mail::Message type object.

Upvotes: 1

Related Questions