在这里做任务。刚刚介绍了 Redcarpet 和 Markdown 转换方法。
这是放在我的助手里面的:
def markdown_to_html(markdown)
renderer = Redcarpet::Render::HTML.new
extensions = { fenced_code_blocks: true }
redcarpet = Redcarpet::Markdown.new(renderer, extensions)
(redcarpet.render markdown).html_safe
end
我可以像这样在我的视图中调用该方法:
意见/帖子/show.html.erb:
<h1><%= markdown_to_html @post.title %></h1>
<div class="row">
<div class="col-md-8">
<p><%= markdown_to_html @post.body %>
</div>
<div class="col-md-4">
<% if policy(@post).edit? %>
<%= link_to "Edit", edit_topic_post_path(@topic, @post), class: 'btn btn-success' %>
<% end %>
</div>
</div>
现在我必须执行以下操作:
目标是像这样呈现降价:
<%= post.markdown_title %>
<%= post.markdown_body %>
将 Post#markdown_title 和 Post#markdown_body 添加到 Post:
创建 markdown_title 和 markdown_body 可以调用的私有 Post#render_as_markdown 方法。这将保持 markdown_title 和 markdown_body DRY。
从 application_helper.rb 中删除 markdown_to_html 方法。
更新您的视图以使用 Post#markdown_title 和 Post#markdown_body 方法。
到目前为止,我一直试图这样做:
模型/post.rb:
class Post < ActiveRecord::Base
has_many :comments
belongs_to :user
belongs_to :topic
# Sort by most recent posts first
default_scope { order('created_at DESC') }
# Post must have at least 5 characters in the title
validates :title, length: { minimum: 5 }, presence: true
# Post must have at least 20 characters in the body
validates :body, length: { minimum: 20 }, presence: true
# Post must have an associated topic and user
validates :topic, presence: true
validates :user, presence: true
def render_as_markdown(markdown)
renderer = Redcarpet::Render::HTML.new
extensions = { fenced_code_blocks: true }
redcarpet = Redcarpet::Markdown.new(renderer, extensions)
(redcarpet.render markdown).html_safe
end
private
def markdown_title(markdown)
render_as_markdown(markdown).title
end
def markdown_body(markdown)
render_as_markdown(markdown).body
end
end
如果我们回到我的views/posts/show.html.erb:
<h1><%= @post.title.markdown_title %></h1>
将渲染:
帖子中的 NoMethodError#show
undefined method `markdown_title' for "chopper mag":String
Extracted source (around line #1):
<h1><%= @post.title.markdown_title %></h1>
<div class="row">
<div class="col-md-8">
<p><%= markdown_to_html @post.body %>
</div>
我做错了什么,我该如何纠正这个问题?
非常感谢。