mercredi 6 mai 2015

Redcarpet Markdown Conversion Method, NoMethodError

Working on an assignment here. Was just introduced to Redcarpet and the Markdown conversion Method.

This was placed inside my Helper:

  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

And I could call the method in my views like so:

views/posts/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>

Now I have to do the following:

The goal is to render markdown like so:

<%= post.markdown_title %>
<%= post.markdown_body %>

Add Post#markdown_title and Post#markdown_body to Post:

Create a private Post#render_as_markdown method that markdown_title and markdown_body can call. This will keep the markdown_title and markdown_body DRY.

Remove the markdown_to_html method from application_helper.rb.

Update your views to use the Post#markdown_title and Post#markdown_body methods.

I have so far attempted to do this:

models/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

If we go back to my views/posts/show.html.erb:

<h1><%= @post.title.markdown_title %></h1>

Will render:

NoMethodError in Posts#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>

What am I doing wrong and how can I rectify this issue?

Thanks kindly.

Aucun commentaire:

Enregistrer un commentaire