如何在 Rails 模型中 render_to_string ?
如何在 Rails 模型中render_to_string
?
如果您这样说,“您永远不应该渲染模型中的任何内容。任何渲染——根本上——都是控制器和视图的责任。”听我说完,或者提出一个可以解决问题的更好方法
。我的模型是邮件程序。只是不是电子邮件、传真。
How do I render_to_string
in a model in rails?
If you say that, "You should never be rendering anything from a model. Any rendering -- at all -- is the responsibility of the controller and view." Hear me out, or suggest a better way you might solve the problem
My model is a mailer. Just not that of emails, faxes.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是工作代码:
在 Rails 2.3.14 上测试。请注意,我没有找到这个想法,只是将其包装在一个方便的方法中。
当然,不要因此认为我提倡在模型中渲染视图;-)
Here's working code:
Tested on Rails 2.3.14. Note that I didn't find this idea, but just wrapped it in a convenience method.
Of course, don't assume that I advocate views rendering in models because of this ;-)
如果您正在寻找一个优雅的解决方案,也许您可以实现 ActionFaxer::Base。您可以跟踪 ActionMailer:: 的实现基本,但专门用于传真。采用这种方法应该可以让您访问 render_to_string。
值得注意的是,在这种情况下,您不会将 render_to_string 添加到模型中,而是引入 Faxer 的概念,它将处理模型。
如果您只需要在模型中渲染模板的任意支持,您可以直接针对 erb 或其他模板语言实现进行编码。
传真机概念的好处在于,它可以抽象出更多内容,而不仅仅是渲染,包括调度、排队和保证交付等内容。
如果你成功了,也许当你完成后你可以把它变成一颗宝石。
If you're looking for an elegant solution, perhaps you could implement an ActionFaxer::Base. You'd be able to follow the implementation of ActionMailer::Base but specialize it for faxes. Taking this approach should give you access to render_to_string.
Of note, in this case you wouldn't be adding render_to_string to a model, but instead introducing the concept of a Faxer, which would deal with models.
If you just need arbitrary support for rendering templates within a model you could code directly against erb or another template language implementation.
The nice thing about the Faxer concept is that it could abstract away more then simply rendering to include things like dispatching, queueing and guaranteeing delivery.
If you're successful, maybe when you're done you could turn it into a gem.
如果你发现这个并想在 Rails 3 上执行此操作,这个要点很有帮助:
https://gist .github.com/aliang/1022384
If you find this and want to do this on Rails 3, this gist was a big help:
https://gist.github.com/aliang/1022384