views:

81

answers:

1

I'm using BlueCloth to create html from markdown from the content my users enter into a textarea like this:

def create
  @post = Post.new(params[:post]) do |post|
    body = BlueCloth.new(post.body) 
    post.body = body.to_html
  end

...

end

This works great! I get the html stored in the database fine, But how do I show markdown in the textarea when the user edits? I tried:

def edit
  @post = Post.find(params[:id])
  @post.body = BlueCloth.new(@post.body)
  @post.body.text
end

The output in my textarea looks like:

#<BlueCloth:0x10402d578>
+2  A: 

Bluecloth's documentation isn't very well defined. I'm not sure there's an easy way to convert html => markdown.

However, there's nothing stopping you storing the markdown in your database, and convert it to html as necessary.

If you want html to be the default returned by @post.body, then you could always override the accessor.

class Post < ActiveRecord::Base
  ...
  def body
    BlueCloth.new(@body).to_html
  end

  def markdown
    @body
  end
end

Now @post.body returns the html version of the markdown. while @post.markdown returns the markdown source.

EmFi
Yah that's a good point, I may have to do that for now. I was hoping to forgo having to run that method on text every time it renders by just storing the html after it saves.
Joseph Silvashy
You raise an interesting point. I've updated my solution with a work around.
EmFi
Optionally, you could store the rendered HTML in a separate column in your Post table.
berkes