Created
August 12, 2011 00:17
-
-
Save onethirtyfive/1141150 to your computer and use it in GitHub Desktop.
Grape presenters?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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