Skip to content

Instantly share code, notes, and snippets.

@jwilger
Created August 10, 2016 22:52
Show Gist options
  • Save jwilger/5c26f09a0d2a2d7d5512bd45aab9290b to your computer and use it in GitHub Desktop.
Save jwilger/5c26f09a0d2a2d7d5512bd45aab9290b to your computer and use it in GitHub Desktop.
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