Last active
August 22, 2019 16:14
-
-
Save jgaskins/966e94cf2c54785d72c0d4a89e21985b to your computer and use it in GitHub Desktop.
Stream results from the database into Ruby objects
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
require 'ostruct' | |
Post = Comment = User = OpenStruct | |
class PostsWithComments | |
def call | |
results = Model.connection.execute <<~SQL | |
SELECT | |
posts.id, | |
posts.title, | |
posts.published_at, | |
comments.id, | |
comments.body, | |
comments.created_at, | |
users.id, | |
users.name | |
FROM posts | |
LEFT JOIN comments ON comments.post_id = posts.id | |
LEFT JOIN users ON comments.author_id = users.id | |
WHERE posts.published_at < now() | |
ORDER BY posts.published_at DESC, comments.created_at DESC | |
SQL | |
results.each do |row| | |
post = Post.new( | |
id: row[0], | |
title: row[1], | |
published_at: Time.parse(row[2]), | |
) | |
comment = Comment.new( | |
id: row[3], | |
title: row[4], | |
created_at: Time.parse(row[5]), | |
) | |
author = User.new( | |
id: row[6], | |
name: row[7], | |
) | |
yield post, comment, author | |
end | |
end | |
end | |
PostsWithComments.new.call do |post, comment, author| | |
# ... | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment