Class: Graphshaper::JsonAdapter

Inherits:
Object
  • Object
show all
Defined in:
lib/graphshaper/adapters/json_adapter.rb

Overview

An adapter to generate JSON files in the format specified by Michael Hackstein

Instance Method Summary collapse

Constructor Details

#initialize(base_path, file_class = File) ⇒ JsonAdapter

Returns a new instance of JsonAdapter.


4
5
6
7
8
# File 'lib/graphshaper/adapters/json_adapter.rb', line 4

def initialize(base_path, file_class = File)
  @base_path = base_path
  @file_class = file_class
  @vertex_file_names = []
end

Instance Method Details

#add_edge(edge_id, from_id, to_id) ⇒ Object


10
11
12
13
14
15
# File 'lib/graphshaper/adapters/json_adapter.rb', line 10

def add_edge(edge_id, from_id, to_id)
  file_name = "#{@base_path}/#{from_id}.json"
  file = @file_class.new(file_name, "a")
  file.write(%Q<{"id":#{to_id}},>)
  file.close
end

#add_vertex(vertex_id) ⇒ Object


17
18
19
20
21
22
23
# File 'lib/graphshaper/adapters/json_adapter.rb', line 17

def add_vertex(vertex_id)
  file_name = "#{@base_path}/#{vertex_id}.json"
  @vertex_file_names << file_name
  file = @file_class.new(file_name, "w")
  file.write(file_header(vertex_id))
  file.close
end

#closeObject


25
26
27
28
29
30
31
32
# File 'lib/graphshaper/adapters/json_adapter.rb', line 25

def close
  @vertex_file_names.each do |file_name|
    content = @file_class.read(file_name).gsub(/,\z/, '')
    file = @file_class.new(file_name, "w+")
    file.write("#{content}]}")
    file.close
  end
end