1

我无法弄清楚为什么@delivery_options无法从各个邮件程序方法中访问实例变量...

class UserMailer < ActionMailer::Base

    @delivery_options = {
            user_name: 'foo',
            password: 'bar',
            address: 'smtp.foobar.net'
    }

    def invite_email (email, project)
        logger.debug( @delivery_options ) #WHY IS THIS IS UNDEFINED??
        @project = project

        #THIS WORKS FINE
        mail(to: email, subject: "WORK DAMMIT", delivery_method_options: {
                user_name: 'foo',
                password: 'bar',
                address: 'smtp.foobar.net'
        })

        #THIS FAILS
        #mail(to: email, subject: "WORK DAMMIT", delivery_method_options: @delivery_options)

    end


end
4

2 回答 2

3

If these are "static" data, you could just do:

class UserMailer < ActionMailer::Base

    DELIVERY_OPTIONS = {
        user_name: 'foo',
        password: 'bar',
        address: 'smtp.foobar.net'
    }

    def invite_email(email, project)
        mail(to: email, subject: "WORK DAMMIT", delivery_method_options: DELIVERY_OPTIONS)
        ...
    end
end

This should work.

If you want to use an instance variable, you should do something like:

class UserMailer < ActionMailer::Base

    def initialize
        @delivery_options = {
            user_name: 'foo',
            password: 'bar',
            address: 'smtp.foobar.net'
        }
    end

    def invite_email(email, project)
        mail(to: email, subject: "WORK DAMMIT", delivery_method_options: @delivery_options)
        ...
    end
end

This way, the variable is defined on the instance of UserMailer you are using. The way you did it was defining an instance variable on the UserMail class.

于 2013-09-19T16:40:16.983 回答
2

第一个实例变量定义 ( @delivery_options) 仅对类可用,对其方法不​​可用。这就是你遇到这个问题的原因。类变量 ( @@delivery_options) 可用于类中的所有方法,但不常用,因为类变量本质上不是线程安全的。

综上所述,您可能希望使用一个常量来定义这些并仅引用该常量。或者,更好的是,使用ActionMailer 的默认系统设置一些默认交付选项,如下所示:

class UserMailer < ActionMailer::Base
  default {user_name: 'foo', password: 'bar', address: 'smtp.foobar.net'}

  ...
end

所有默认值都应用于邮件程序中的每个方法,但会被您在本地指定的任何选项覆盖。

于 2013-09-19T16:53:53.450 回答