首页 > 解决方案 > 访问外部上下文的自我

问题描述

我有一些看起来像这样的代码:

  class Wrapper
    def get_email_body rdv
      body = "<h1>There is an appointment available!</h1><br>"
      body += "Title: <b>#{rdv['title']}</b><br>"
      body += "Date: <b>#{rdv['start']}</b><br>"
      body + "Link: <a href='#{rdv['link']}'>"
    end

    def send_email rdv
      TARGET_EMAIL_ADDRESSES.each do|email|
        Mail.deliver do
          to email
          from 'my_email_address'
          subject 'Appointments available!'
          html_part do
            content_type 'text/html; charset=UTF-8'
            body get_email_body(rdv)
          end
        end
      end
    end
  end

send_email使用代表约会的对象调用时,我得到异常:

  /var/lib/gems/2.7.0/gems/mail-2.7.1/lib/mail/message.rb:1396:in `method_missing': undefined method `get_email_body' for #<Mail::Part:0x000055ba3e9f60c0> (NoMethodError)

我注意到给 Mail.deliver 的块内部self是一个#<Mail::Part:560, Multipart: false, Headers: <Content-Type: text/html; charset=UTF-8>>对象。

我知道该块是由 Mail 类的实例方法运行的,这self就是不同的原因。

是否可以访问self外部上下文的 Wrapper 对象并调用get_email_body实例方法?最好不要使其成为类方法。

谢谢。

标签: rubyoopemail

解决方案


在调用之前评估电子邮件正文Mail.deliver

def send_email(rdv)
  email_body = get_email_body(rdv) # evaluate

  TARGET_EMAIL_ADDRESSES.each do |email|
    Mail.deliver do
      to email
      from 'my_email_address'
      subject 'Appointments available!'
      html_part do
        content_type 'text/html; charset=UTF-8'
        body email_body # pass the value
      end
    end
  end
end

推荐阅读