【问题标题】:Why Rails instance method can be used as class method in rspec为什么 Rails 实例方法可以用作 rspec 中的类方法
【发布时间】:2015-08-09 00:28:14
【问题描述】:

我在一篇关于在 Rails 应用程序中发送邮件的文章中发现了一个 sn-p:

class ExampleMailerPreview < ActionMailer::Preview
  def sample_mail_preview
    ExampleMailer.sample_email(User.first)
  end
end

在此链接中:http://www.gotealeaf.com/blog/handling-emails-in-rails

我不知道为什么方法:sample_email(),在我看来应该是一个实例方法,可以像ExampleMailer.sample_email()这里的类方法一样访问。谁能解释一下?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 rspec actionmailer


    【解决方案1】:

    这不是 rspec 的事情,而是 ActionMailer 的事情。正在看:

    https://github.com/rails/rails/blob/master/actionmailer/lib/action_mailer/base.rb

    看看第 135-146 行的 cmets:

    # = Sending mail
    #
    # Once a mailer action and template are defined, you can deliver your message or defer its creation and
    # delivery for later:
    #
    #   NotifierMailer.welcome(User.first).deliver_now # sends the email
    #   mail = NotifierMailer.welcome(User.first)      # => an ActionMailer::MessageDelivery object
    #   mail.deliver_now                               # generates and sends the email now
    #
    # The <tt>ActionMailer::MessageDelivery</tt> class is a wrapper around a delegate that will call
    # your method to generate the mail. If you want direct access to delegator, or <tt>Mail::Message</tt>,
    # you can call the <tt>message</tt> method on the <tt>ActionMailer::MessageDelivery</tt> object.
    

    该功能是通过在 ActionMailer::Base 类上定义一个 method_missing 方法来实现的,如下所示:

      def method_missing(method_name, *args) # :nodoc:
        if action_methods.include?(method_name.to_s)
          MessageDelivery.new(self, method_name, *args)
        else
          super
        end
      end
    

    本质上,在 ActionMailer 实例(注释示例中的 NotifierMailer)上定义一个方法,然后在类上调用它会创建一个新的 MessageDelivery 实例,该实例委托给 ActionMailer 类的一个新实例。

    【讨论】:

    • 委托给 Mail::Message 对象的一个​​新实例。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2018-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多