Skip to content

Instantly share code, notes, and snippets.

@javigomez
Last active October 23, 2017 14:13
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 javigomez/b0a902ab8fd3cfa0e18460e1629788d2 to your computer and use it in GitHub Desktop.
Save javigomez/b0a902ab8fd3cfa0e18460e1629788d2 to your computer and use it in GitHub Desktop.
nested to_json in ruby
# 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