Skip to content

Instantly share code, notes, and snippets.

@wojtha
Last active July 27, 2018 14:46
Show Gist options
  • Save wojtha/716bab0d92e73942dd6fd458a19b21ab to your computer and use it in GitHub Desktop.
Save wojtha/716bab0d92e73942dd6fd458a19b21ab to your computer and use it in GitHub Desktop.
Using Jbuilder outside jbuilder templates. See https://buttercms.com/blog/json-serialization-in-rails-a-complete-guide
require 'jbuilder'
Post = Struct.new(:id, :title, :content, :comments)
Comment = Struct.new(:id, :author, :body)
class PostWithCommentsSerializer
attr_reader :object
def initialize(object)
@object = object
end
def jbuild(*args, &block)
Jbuilder.new(*args, &block).attributes!
end
def to_json
jbuild do |json|
json.id object.id
json.title object.title
json.content object.content
json.comments(object.comments) do |comment|
json.id comment.id
json.author comment.author
json.body comment.body
end
end
end
end
post = Post.new('first', 'First Post', 'Welcome to our site', [
Comment.new(1, 'Marek', 'Great!'),
Comment.new(2, 'Riki', ':grumpycat:'),
])
puts PostWithCommentsSerializer.new(post).to_json
# {"id"=>"first", "title"=>"First Post", "content"=>"Welcome to our site", "comments"=>[{"id"=>1, "author"=>"Marek", "body"=>"Great!"}, {"id"=>2, "author"=>"Riki", "body"=>":grumpycat:"}]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment