Module: Tree::Utils::JSONConverter
- Included in:
- TreeNode
- Defined in:
- lib/tree/utils/json_converter.rb
Overview
Provides utility methods to convert a TreeNode to and from JSON.
Every serialized node carries its Ruby class name under the json_class
key. With the json gem 2.x this is the key the gem inspects itself when
parsing with create_additions: true. The json gem 3.x removed that
option together with the JSON.create_id accessor, so RubyTree emits the
key on its own and rebuilds the nodes through ClassMethods#from_json,
which relies on the on_load parser callback available in both the json
gem 2.x and 3.x.
Defined Under Namespace
Modules: ClassMethods
Constant Summary collapse
- JSON_CLASS_KEY =
The hash key which carries the Ruby class name of a serialized node. Equals the default
JSON.create_idof the json gem 2.x, so documents written by earlier RubyTree versions stay readable. 'json_class'
Converting to/from JSON collapse
-
#as_json(_options = {}) ⇒ Object
Creates a JSON ready Hash for the #to_json method.
-
#to_json(*args) ⇒ Object
Creates a JSON representation of this node including all it's children.
Class Method Summary collapse
-
.included(base) ⇒ Object
Extend the base class with the converter class methods.
Class Method Details
.included(base) ⇒ Object
Extend the base class with the converter class methods.
61 62 63 |
# File 'lib/tree/utils/json_converter.rb', line 61 def self.included(base) base.extend(ClassMethods) end |
Instance Method Details
#as_json(_options = {}) ⇒ Object
Creates a JSON ready Hash for the #to_json method.
Rails uses JSON in ActiveSupport, and all Rails JSON encoding goes through
as_json.
noinspection RubyUnusedLocalVariable
82 83 84 85 86 87 88 89 90 91 92 |
# File 'lib/tree/utils/json_converter.rb', line 82 def as_json( = {}) json_hash = { name: name, content: content, JSON_CLASS_KEY => self.class.name } json_hash['children'] = children if children? json_hash end |
#to_json(*args) ⇒ Object
Creates a JSON representation of this node including all it's children. This requires the JSON gem to be available, or else the operation fails with a warning message. Uses the Hash output of #as_json method.
106 107 108 |
# File 'lib/tree/utils/json_converter.rb', line 106 def to_json(*args) as_json.to_json(*args) end |