Created
May 7, 2014 18:25
-
-
Save teamon/1a2ed0cc144737441729 to your computer and use it in GitHub Desktop.
Ruby representers without a library
This file contains 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
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 |
This file contains 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
# 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