ruby-on-rails - ActionMailer 实例方法像类方法一样使用

标签 ruby-on-rails ruby

这是 ActionMailer 指南中的一个简短片段

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

  def welcome_email(user)
    @user = user
    @url  = "http://example.com/login"
    mail(:to => user.email,
         :subject => "Welcome to My Awesome Site")
  end

end

在 Controller 中

class UsersController < ApplicationController
  # POST /users
  # POST /users.xml
  def create
    @user = User.new(params[:user])

    respond_to do |format|
      if @user.save
        # Tell the UserMailer to send a welcome Email after save
        UserMailer.welcome_email(@user).deliver

        format.html { redirect_to(@user, :notice => 'User was successfully created.') }
        format.xml  { render :xml => @user, :status => :created, :location => @user }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @user.errors, :status => :unprocessable_entity }
      end
    end
  end
end

那么为什么 Rails 试图将 ruby​​ist 与实例方法混淆为类方法?我假设他们已经覆盖了缺失的方法,但这只是为了混淆!或者我在这里遗漏了什么?

即为什么不将 welcome_email 定义为 def self.welcome_email(user)

最佳答案

如果是#self.welcome_email,你必须自己创建一个类的实例,这需要对所有默认参数等进行一些配置。Rails 只是提供相同的工厂方法姓名。

快速浏览一下源代码,您是对的,它似乎确实使用了method_missing,其中邮件程序实际上是通过以下方式创建的:

mailer = TheMailer.new(:welcome_email, *args)

Rails 做了很多像这样的“巫术”事情,通常只是为了节省您编写的代码量。仅将 #welcome_email 更改为类方法不会为您提供实例。

关于ruby-on-rails - ActionMailer 实例方法像类方法一样使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6367921/

相关文章:

ruby-on-rails - 如何查询Noticed gem json字段

ruby-on-rails - rails 。如何存储一天中的时间(用于日程安排)?

ruby-on-rails - Rails 范围适用于 SQLite 和 MySQL,但不适用于 Heroku (PostgreSQL)

ruby-on-rails - Rails:我们什么时候必须在 rails 的某些类之前放置::理解基类

ruby-on-rails - 如何使用 Rails 配置 Twilio 短信网关?

ruby-on-rails - 在 rails3 中使用观察者自定义回调

javascript - 更改输入值基于

sql-server - 使用 Ruby、ODBC 和 FreeTDS 从 Mac 连接到 MS SQL Server 2005

ruby - 我可以实现四舍五入吗?

c - 应该如何在 Ruby 扩展中对 VALUE* 数组进行标记?