简体   繁体   English

如何辨别Ruby类和实例方法之间的区别

[英]How To Tell The Difference Between Ruby Class and Instance Methods

Here is some code in a recent Railscast: 以下是最近Railscast中的一些代码:

class UserMailer < ActionMailer::Base
  default from: "from@example.com"

  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. 对我来说, password_reset方法看起来像一个实例方法,但它看起来像是一个类方法。 Is it an instance or a class method, or is there something special about this UserMailer class? 它是实例还是类方法,或者这个UserMailer类有什么特别之处吗?

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. 查看源代码( https://github.com/rails/rails/blob/master/actionmailer/lib/action_mailer/base.rb),Rails使用method_missing创建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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM