Skip to content

Instantly share code, notes, and snippets.

@jgaskins
Last active August 22, 2019 16:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jgaskins/966e94cf2c54785d72c0d4a89e21985b to your computer and use it in GitHub Desktop.
Save jgaskins/966e94cf2c54785d72c0d4a89e21985b to your computer and use it in GitHub Desktop.
Stream results from the database into Ruby objects
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