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.

Defined Under Namespace

Modules: ClassMethods

Converting to/from JSON collapse

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object


45
46
47
# File 'lib/tree/utils/json_converter.rb', line 45

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

Parameters:

  • options (Object) (defaults to: {})

Returns:

  • A hash based representation of the JSON

See Also:

Author:

Since:

  • 0.8.3


66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/tree/utils/json_converter.rb', line 66

def as_json(options = {})

  json_hash = {
      name: name,
      content: content,
      JSON.create_id => self.class.name
  }

  if has_children?
    json_hash['children'] = children
  end

  json_hash

end

#to_json(*a) ⇒ 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.

Returns:

  • The JSON representation of this subtree.

See Also:

Author:

Since:

  • 0.7.0


94
95
96
# File 'lib/tree/utils/json_converter.rb', line 94

def to_json(*a)
  as_json.to_json(*a)
end