ek_ny
ek_ny

Reputation: 10243

How To Tell The Difference Between Ruby Class and Instance Methods

Here is some code in a recent Railscast:

class UserMailer < ActionMailer::Base
  default from: "[email protected]"

  def password_reset(user)
    @user = user
    mail :to => user.email, :subject => "Password Reset"
  end
end

and this is in a controller

def create
  user = User.find_by_email(params[:email])
  UserMailer.password_reset(user).deliver
  redirect_to :root, :notice => "Email sent with password reset instructions."
end

The password_reset method looks like an instance method to me, yet it looks like it's being called like a class method. Is it an instance or a class method, or is there something special about this UserMailer class?

Upvotes: 0

Views: 167

Answers (1)

Yehuda Zargarov
Yehuda Zargarov

Reputation: 277

Looking in the source (https://github.com/rails/rails/blob/master/actionmailer/lib/action_mailer/base.rb), Rails uses method_missing to create a new instance of the ActionMailer. Here's the relevant part from the source:

def method_missing(method_name, *args) # :nodoc:
  if respond_to?(method_name)
    new(method_name, *args).message
  else
    super
  end
end

Upvotes: 2

Related Questions