Last active
October 23, 2017 14:13
-
-
Save javigomez/b0a902ab8fd3cfa0e18460e1629788d2 to your computer and use it in GitHub Desktop.
nested to_json in ruby
This file contains 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 'active_support' | |
# require 'active_support/core_ext' | |
require 'json' | |
require 'values' | |
class Statement < Value.new(:title, :description) | |
def to_json(state = nil) | |
{ | |
title: title, | |
properties: { | |
description: description | |
} | |
}.to_json(state) | |
end | |
def self.sample | |
with( | |
title: 'this is a title', | |
description: 'this is a description' | |
) | |
end | |
end | |
class Form < Value.new(:blocks) | |
def to_json(state = nil) | |
{ | |
fields: blocks | |
}.to_json(state) | |
end | |
def self.sample | |
with( | |
blocks: [ | |
Statement.sample, | |
Statement.sample | |
] | |
) | |
end | |
end | |
form = Form.sample | |
puts form.to_json | |
# returns: | |
# { | |
# "fields": [ | |
# { | |
# "title": "this is a title", | |
# "properties": { | |
# "description": "this is a description" | |
# } | |
# }, | |
# { | |
# "title": "this is a title", | |
# "properties": { | |
# "description": "this is a description" | |
# } | |
# } | |
# ] | |
# } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment