Class: RailsGraph::Exporters::Cypher

Inherits:
Base
  • Object
show all
Defined in:
lib/rails_graph/exporters/cypher.rb

Constant Summary collapse

BASE_CYPHER =
"MATCH (n) DETACH DELETE n;"

Class Method Summary collapse

Class Method Details

.build_queries(graph) ⇒ Object



16
17
18
19
20
21
22
23
24
# File 'lib/rails_graph/exporters/cypher.rb', line 16

def self.build_queries(graph)
  queries = []
  queries << BASE_CYPHER

  graph.nodes.each { |node| queries << create_node_cypher(node) }
  graph.relationships.each { |relationship| queries << create_relationship_cypher(relationship) }

  queries
end

.create_node_cypher(node) ⇒ Object



46
47
48
49
50
51
52
# File 'lib/rails_graph/exporters/cypher.rb', line 46

def self.create_node_cypher(node)
  ref = node_ref(node)
  labels = node.labels.join(":")
  properties = format_properties(node)

  "CREATE (#{ref}:#{labels} {#{properties}})"
end

.create_relationship_cypher(relationship) ⇒ Object



54
55
56
57
58
59
# File 'lib/rails_graph/exporters/cypher.rb', line 54

def self.create_relationship_cypher(relationship)
  source_ref = node_ref(relationship.source)
  target_ref = node_ref(relationship.target)

  "CREATE (#{source_ref})-[:#{relationship.label} {#{format_properties(relationship)}}]->(#{target_ref})"
end

.escape_quotes(value) ⇒ Object



61
62
63
64
65
# File 'lib/rails_graph/exporters/cypher.rb', line 61

def self.escape_quotes(value)
  return value if value.is_a? Symbol

  value.gsub("'") { "\\'" }
end

.export(graph:, filename:) ⇒ Object



10
11
12
13
14
# File 'lib/rails_graph/exporters/cypher.rb', line 10

def self.export(graph:, filename:)
  queries = build_queries(graph)

  File.write(filename, queries.join("\n"), mode: "w")
end

.format_properties(item) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/rails_graph/exporters/cypher.rb', line 30

def self.format_properties(item)
  output = "name: '#{item.name}'"

  item.properties.each do |k, v|
    formatted_value = case v
                      when String, Symbol then "'#{escape_quotes(v)}'"
                      when nil then "null"
                      else v.to_s
                      end

    output += ", #{k}: #{formatted_value}"
  end

  output
end

.node_ref(node) ⇒ Object



26
27
28
# File 'lib/rails_graph/exporters/cypher.rb', line 26

def self.node_ref(node)
  "ref_#{node.id.gsub("-", "_")}"
end