Skip to content

Instantly share code, notes, and snippets.

@onethirtyfive
Created August 12, 2011 00:17
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save onethirtyfive/1141150 to your computer and use it in GitHub Desktop.
Save onethirtyfive/1141150 to your computer and use it in GitHub Desktop.
Grape presenters?
# lib/api/presenters/detailed_post.rb
module API
module Presenters
class DetailedPost
include ActiveModel::Serializers::JSON
include ActiveModel::Serializers::Xml
attr_accessor :post
delegate :attributes, :to => :post
def initialize(post, *args)
options = args.extract_options!
@format = options.delete(:preprocess)
@post = post
end
def serializable_hash(options = nil)
output = post.serializable_hash(options)
output[:body] = preprocess(output.delete(:body), @format)
output[:comments] = post.comments.collect do |comment|
preprocess(comment[:body], @format)
end
output
end
private
def preprocess(content, format)
case format
when :markdown
# transform markdown into html
end
end
end
end
end
# blog_api.rb
class BlogAPI < API::Grape
presenter :detailed, :class => API::Presenters::DetailedPost
get '/posts' do
@posts = Post.where({:published => true})
present @posts, :as => :detailed, :preprocess => :markdown
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment