Q:

Include arbitrary field in Rails model JSON output

I'm using Rails as a REST server, and one of my models has a description field. In that model's JSON representation, I need to output both the regular description field AND an arbitrary non-DB attribute called description_markdown that is just the description run through a markdown filter. I already know how to run text through markdown using redcarpet, like:
@post = Post.find(params[:id])
markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML, :autolink => true, :space_after_headers => true, :fenced_code_blocks => true, :lax_html_blocks => true)
description_markdown = markdown.render(@post.description).html_safe

But what I really need is to make description_markdown an attribute on @post (like @post.description_markdown), and have it output in @post's JSON representation. 

A:

I normally use RABL gem to build JSON views for my APIs -- it gives you a lot of flexibility on building JSON responses, such as creating custom child nodes, adding arbitrary code. Check it out.
But, to answer your question, you can probably overwrite as_json method of Post to include the return of description_markdown. Something like (not tested):
#post.rb
class Post < ActiveRecord::Base

  def description_markdown
    ...
  end
  ...
  def as_json(options)
    super(:only => [:attributes_you_want], :methods => [:description_markdown])
  end
  ...
end

Then, in controller:
render :json => @post

Hope, it helps.

