ruby - 访问外部上下文的自我
问题描述
我有一些看起来像这样的代码:
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
实例方法?最好不要使其成为类方法。
谢谢。
解决方案
在调用之前评估电子邮件正文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
推荐阅读
- python-pptx - 用于将系列移动到辅助轴的 Python PPTX 解决方法功能
- php - 如何以正确的顺序返回 php html?
- reactjs - 无法有条件地为下拉菜单工作
- c - 分解文件时出现分段错误(核心转储)
- python - 尝试在本地运行 django 项目时收到错误消息
- angular - 角度路由保护/解析器 - 类型'Observable
' 不可分配给类型 'Observable ' - spring-boot - SpringBoot 的 bootBuildImage 与 Kaniko 而不是 Docker 守护进程
- javascript - 如何在瞬间显示到最近的小时?
- python - 如何检查opencv是否使用GPU?
- python - 如何更改此程序以使用 random.shuffle 而不是 random.sample?