Note that there are some explanatory texts on larger screens.

plurals
  1. PORails way to offer modified attributes
    text
    copied!<p>The case is simple: I have markdown in my database, and want it parsed on output(*).</p> <p><code>@post.body</code> is mapped to the posts.body column in the database. Simple, default Activerecord ORM. That column stores the markdown text a user inserts.</p> <p>Now, I see four ways to offer the markdown rendered version to my views: </p> <p><strong>First</strong>, in <code>app/models/post.rb</code>:</p> <pre><code># ... def body markdown = RDiscount.new(body) markdown.to_html end </code></pre> <p>Allowing me to simply call @post.body and get an already rendered version. I do see lots of potential problems with that, e.g. on edit the textfield being pre-filled with the rendered HMTL instead of the markdown code.</p> <p><strong>Second</strong> option would be a new attribute in the form of a method</p> <p>In <code>app/models/post.rb</code>:</p> <pre><code># ... def body_mardownified markdown = RDiscount.new(body) markdown.to_html end </code></pre> <p>Seems cleanest to me.</p> <p>Or, <strong>third</strong> in a helper in <code>app/helpers/application_helper.rb</code></p> <pre><code>def markdownify(string) markdown = RDiscount.new(string) markdown.to_html end </code></pre> <p>Which is used in the view, instead of <code>&lt;%= body %&gt;</code>, <code>&lt;%= mardownify(body) %&gt;</code>.</p> <p>The <strong>fourth</strong> way, would be to parse this in the <code>PostsController</code>. </p> <pre><code>def index @posts = Post.find(:all) @posts.each do |p| p.body = RDiscount.new(string).to_html @rendered_posts &lt;&lt; p end end </code></pre> <p>I am not too familiar with Rails 3 proper method and attribute architecture. How should I go with this? Is there a fifth option? Should I be aware of gotchas, pitfalls or performance issues with one or another of these options?</p> <p>(*) In future, potentially updated with a database caching layer, or even special columns for rendered versions. But that is beyond the point, merely pointing out, so to avoid discussion on filter-on-output versus filter-on-input :).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload