Rails - How to save partial HAML HTML as a string to send to an external service?

Hey guys, first post here, hope you can help me.

We generate a newsletter automatically every 24 hours using the rake task. There is a section at the top of the newsletter where the administrator can post a customized message. The screen that the administrator uses has a live preview of the newsletter (they were persistent in this) displayed using a partial haml that accepts the collection.

In order to generate and send emails, we send XML documents to a third-party API that contains (among other things) HTML for the letter we would like to generate.

What I want to do is to save the result of this partial part of haml as part of the rake task, something similar to the PHP ob _ * () buffering function. Is there a way to do something like the following:

ob_start();
render :partial => newsletter, :collection => posts
newsletter_html = ob_get_contents()
xml = "
<Creative>
  <Name>Our Newsletter -- #{Time.now.strftime('%m/%d/%Y')}</Name>
  <HTML>&lt;html&gt;&lt;body&gt;#{newsletter_html}&lt;/body&gt;&lt;/html&gt;</HTML>
  ...
</Creative>"

I probably lack something obvious, and I could think of several ways to do this, but most of them are NOT DRY, and I don’t want to generate a lot of html in helpers, models or the task itself.

Let me know if I have a way to do this. Thanks.

+3
source share
3 answers

A common way to do this (which is usually not recommended) is to convert to a string in your model or rake task:


cached_content = 
  ActionView::Base.new(Rails::Configuration.new.view_path).render(:partial => "newsletter", :locals => {:page => self,:collection => posts})

. : http://www.compulsivoco.com/2008/10/rendering-rails-partials-in-a-model-or-background-task/

, . - , , .

http://guides.rubyonrails.org/caching_with_rails.html

+2

HAML docs:

require 'haml'
haml_string = "%p Haml-tastic!"
engine = Haml::Engine.new(haml_string)
engine.render #=> "<p>Haml-tastic!</p>\n"

HAML , , .

+3

, rdoc Haml, , , .

ERB :

require 'erb'

name = 'world'
template = 'hello <%= name %>'
template = ERB.new(template)
puts template.result(binding)
0

Source: https://habr.com/ru/post/1714888/


All Articles