ruby-on-rails - rails : Render view content in post-processor (model/helper issues)

标签 ruby-on-rails view-helpers

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

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

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

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

[[PRODUCT#ID:123]] 是我自己的标记语言和 是红地毯。我使用 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."

“苹果”部分是从 View 部分中获取的。

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

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

问题

基本上,我想使用 BlogPost 和文章模型中的 :before_save ,但后来我遇到了尝试从模型中做助手的问题,这一切都变得困惑。

我尝试使用:
ApplicationController.helpers.render_content(@blog_post.unprocessed_content)

但是它找不到像/blog_post/product_item_with_pic 这样的 View 部分。感觉就像我会继续遇到这样的问题。

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

我的问题
  • 解决这个问题的最优雅的方法是什么?
  • 如果没有真正的好方法,至少,当我从模型中像这样调用 ApplicationHelper 时,如何访问部分?
  • 最佳答案

    我不确定我完全理解你想要什么。但是要在标准流程之外使用 Rails View 渲染功能,应该使用 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有关如何在渲染器内部提供帮助程序的信息。

    关于ruby-on-rails - rails : Render view content in post-processor (model/helper issues),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32164914/

    相关文章:

    php - 可以查看助手读取请求

    ruby-on-rails - rails 3,如何在组中设置 user.role#create 操作

    ruby-on-rails - Rails 使用 block 渲染部分内容

    javascript - 我如何使用 jquery 在 <body> 中设置 html 内容

    ruby-on-rails - Rails - 带参数的成员操作 - 路径助手?

    javascript - ZF2 如何在布局中使用页面 javascript 和样式表

    ruby-on-rails - 如何在Rails的 “content_tag”属性中使用HTML实体?

    php - Zend Framework 2 - 如何从库中包含部分内容

    javascript - 测试单击输入字段并生成文本选择

    jquery - 为什么 ruby​​ on rails 返回 null 而不是 json 对象