Created
August 10, 2016 22:52
-
-
Save jwilger/5c26f09a0d2a2d7d5512bd45aab9290b to your computer and use it in GitHub Desktop.
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
class BlogPost < ActiveRecord::Base | |
end | |
class MyBlog::Post | |
attr_accessor :title, :author, :posted_at, :body | |
def initialize(title:, author:, posted_at:, body:) | |
self.title = title | |
self.author = author | |
self.posted_at = posted_at | |
self.body = body | |
freeze | |
end | |
end | |
class MyBlog::PostsRepository < SimpleDelegator | |
def initialize | |
super(BlogPost) | |
end | |
def method_missing(*args, &block) | |
result = super | |
case result | |
when ActiveRecord::Relation | |
if result.many? | |
convert_enumerator(result) | |
else | |
convert(result.first) | |
end | |
else | |
convert(result) | |
end | |
end | |
def convert_enumerator(result) | |
Enumerator.new do |yielder| | |
result.each do |value| | |
yielder << convert(value) | |
end | |
end | |
end | |
def convert(result) | |
case result | |
when BlogPost | |
MyBlog::Post.new(title: result.title, author: result.author, | |
posted_at: result.posted_at, body: result.body) | |
else | |
result | |
end | |
end | |
end | |
MyBlog::PostsRepository.first | |
#=> Returns an instance of MyBlog::Post | |
MyBlog::PostsRepository.all.to_a | |
#=> Returns an Array containing MyBlog::Post elements |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment