ruby-on-rails – Rails:在后处理器中渲染视图内容(模型/助手问题)

我有一个网络应用程序,我也有一个非常复杂的博客类型.对于这个博客,除了自制的标记语言之外,我还使用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]]是我自己的标记语言,很酷的是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中的方法使用例如:
– render partials / blog_post / product_item_with_pic
– RedCarpet标记

我在标记/未处理状态下编写所有文章/博客文章,但在我发布并加载render_content()时,预处理此内容是完全合理的:before_save.

问题

基本上,我想使用:来自BlogPost和Article模型的before_save,但后来我遇到了尝试从模型中做帮助的东西的问题,这一切都变得混乱.

我试过用:

ApplicationController.helpers.render_content(@blog_post.unprocessed_content)

但后来它找不到像/ blog_post / product_item_with_pic这样的视图部分.感觉就像我会继续碰到这样的问题.

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

我的问题

>解决这个问题最优雅的方法是什么?
>如果没有一个方法,至少,当我从模型中调用ApplicationHelper时,如何访问partials?

解决方法

我不确定我完全理解你想要的东西.但是要在标准流程之外使用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

阅读brief documentation获取有关如何在渲染器内提供帮助的信息.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...