Skip to content

Instantly share code, notes, and snippets.

@teamon
Created May 7, 2014 18:25
Show Gist options
  • Save teamon/1a2ed0cc144737441729 to your computer and use it in GitHub Desktop.
Save teamon/1a2ed0cc144737441729 to your computer and use it in GitHub Desktop.
Ruby representers without a library
module PostRepresenter
include Representer
using Representer
def basic(post)
select(post, :id, :name)
end
def details(post)
basic(post) & comments(post)
end
def comments(post)
{ comments: post.comments.map {|c| CommentRepresenter.basic(c) }
end
end
# requires ruby 2.1+
module Representer
extend ActiveSupport::Concern
refine Hash do
alias_method :&, :merge
end
included do
extend self
end
protected
def select(obj, *fields)
fields.map {|field| { field => obj.send(field) } }.inject({}, :merge)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment