Last active
July 27, 2018 14:46
-
-
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
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 '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