ruby-on-rails 在Rails 7.1中使用Redcarpet在Markdown中使用ERB

jslywgbw  于 5个月前  发布在  Ruby
关注(0)|答案(1)|浏览(82)

我正在尝试在Rails 7.1.1应用程序中添加Markdown支持。
红地毯宝石版本是3.6.0。
我遵循这个问题的建议:
Using ERB in Markdown with Redcarpet
我的当前代码(在/config/initializers/markdown_handler.rb中)是:

module MarkdownHandler
  def self.erb
    @erb ||= ActionView::Template.registered_template_handler(:erb)
  end

  def self.call(template, source)
    compiled_source = erb.call(template, source)
    "Redcarpet::Markdown.new(Redcarpet::Render::HTML.new).render(begin;#{compiled_source};end).html_safe"
  end
end

ActionView::Template.register_template_handler :md, MarkdownHandler

字符串
我得到一个错误:
ActionView::Template::Error: wrong argument type ActionView::OutputBuffer (expected String)
有人能解释一下为什么会发生这种情况,以及如何修复它吗?

abithluo

abithluo1#

自定义模板处理程序使用来自ActionView::Template::Handlers::ERB的编译输出。
输出是String,但从Rails 7.1开始,它是ActionView::OutputBufferhttps://github.com/rails/rails/commit/ee68644c284aa7512d06b4b5514b1236c1b63f55)。
提交消息描述了进行此更改的原因:
随着OutputBuffer最近的变化,如果缓冲区后来被连接到,调用to_s将非常昂贵(如果缓冲区从未更改,它应该相对便宜,因为Ruby将共享内存)。
我们看到一个错误:
ActionView::Template::Error: wrong argument type ActionView::OutputBuffer (expected String)
要修复它,我们可以简单地转换为String:

module MarkdownHandler
  def self.erb
    @erb ||= ActionView::Template.registered_template_handler(:erb)
  end

  def self.call(template, source)
    compiled_source = erb.call(template, source)
    "Redcarpet::Markdown.new(Redcarpet::Render::HTML.new).render(begin;#{compiled_source};end.to_s).html_safe"
  end
end

ActionView::Template.register_template_handler :md, MarkdownHandler

字符串

相关问题