Rails: 在后处理器中呈现视图内容(模型/助手问题)

8

我有一个Web应用程序,其中还包含相当复杂的博客类型。对于这个博客,我既使用RedCarpet作为标记语言,又使用自制的标记语言,非常实用。

在我的自制标记语言中,我从应用程序中调用产品视图和其他部分。我在两个不同的模型中使用它:BlogPost和Article。

例如,博客文章可能是这样的:

@blog_post.unprocessed_content = "Today I would like to show you this **cool** product that we offer: [[PRODUCT#ID:123]]." 

[[PRODUCT#ID:123]] 是我自己的标记语言,而 cool 是 RedCarpet。我使用 ApplicationHelper 中的 render_content 方法,如下:

processed_content = render_content(@blog_post.unprocessed_content)

这将会输出

processed_content = "Today I would like to show you a <strong>cool</strong> product that we offer: <h3>Apple</h3><img src="apple.jpg"><p>Apple is a nice fruit.</p>. Price: 1 USD."

“apple”这部分是从视图局部中获取的。

ApplicationHelper 中使用的方法例如: - 渲染局部 /blog_post/product_item_with_pic - RedCarpet 标记语言

我以标记语言/未处理状态撰写所有文章/博客文章,但在发布时对此内容进行预处理并在 :before_save 上加载 render_content() 是完全有意义的。

问题

基本上,我想要在 BlogPost 和 Article 模型 中使用 :before_save,但这将遇到在模型内尝试执行帮助程序操作导致混乱的问题。

我尝试使用:

ApplicationController.helpers.render_content(@blog_post.unprocessed_content)

但是它无法找到像 /blog_post/product_item_with_pic 这样的视图部分。感觉我会一直遇到这样的问题。

现在,我有一个非常丑陋的解决方案(可行),就是在加载视图时在视图中进行预处理。基本上,在 admin::blog_post#show 中,我调用 render_content 然后执行保存。是的,这很丑陋。

我的问题

  1. 最优雅的解决方法是什么?
  2. 如果没有真正好的方法,那么至少在我从模型调用 ApplicationHelper 时如何访问部分内容?

你的 render_content 到底是做什么的还不太清楚。 - EugZol
你说得完全正确,那不是很清楚。我现在已经编辑过了。 - Christoffer
1个回答

2

我不确定我完全理解你想要什么。但是,要在标准流程之外使用Rails视图渲染功能,应该使用render_anywhere Gem。

require 'render_anywhere'

class Article < ActiveRecord::Base
  include RenderAnywhere
  class RenderingController < RenderAnywhere::RenderingController; end

  before_save :process_content
  attr_reader :content

  private

  def process_content
    # This variable will contain resulting HTML
    @content = render(template: 'articles/article', layout: 'articles')
  end
end

阅读简要文档获取将帮助程序嵌入渲染器的信息。


1
是的,我再次阅读了我的问题,发现表述不太清楚。我进行了修改,尝试了您的解决方案,并在自己的函数上进行了一些微调,最终成功了。谢谢! - Christoffer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接