module Redgraph::NodeModel

This mixin allows you to use an interface similar to ActiveRecord

class Actor

include Redgraph::NodeModel

self.graph = Redgraph::Graph.new("movies", url: $REDIS_URL)
self.label = "actor" # optional, if missing it will be extracted from the class name
attribute :name

end

You will then be able to

john = Actor.find(123) total = Actor.count

When you create a record it will automatically set the _type property with the class name. This allows reifying the node into the corresponding NodeModel class.

Attributes

attribute_names[R]
graph[RW]

Public Class Methods

attribute(name) click to toggle source
# File lib/redgraph/node_model.rb, line 40
def attribute(name)
  @attribute_names << name
  attr_accessor(name)
end
new(**args) click to toggle source
# File lib/redgraph/node_model.rb, line 55
def initialize(**args)
  absent_attributes = args.keys.map(&:to_sym) - self.class.attribute_names - [:_type]

  if absent_attributes.any?
    raise ArgumentError, "Unknown attribute #{absent_attributes}"
  end

  args.each do |name, value|
    instance_variable_set("@#{name}", value)
  end
end

Private Class Methods

inherited(subclass) click to toggle source
Calls superclass method
# File lib/redgraph/node_model.rb, line 47
def inherited(subclass)
  super
  subclass.instance_variable_set(:@attribute_names, @attribute_names.dup)
  subclass.instance_variable_set(:@graph, @graph.dup)
end

Public Instance Methods

==(other) click to toggle source
# File lib/redgraph/node_model.rb, line 94
def ==(other)
  attributes == other.attributes && id == other.id
end
assign_attributes(attrs = {}) click to toggle source
# File lib/redgraph/node_model.rb, line 83
def assign_attributes(attrs = {})
  attrs.each do |name, value|
    instance_variable_set("@#{name}", value)
  end
end
attributes() click to toggle source

Object attributes as a hash

# File lib/redgraph/node_model.rb, line 79
def attributes
  self.class.attribute_names.to_h { |name| [name, public_send(name)] }
end
graph() click to toggle source

The current graph

# File lib/redgraph/node_model.rb, line 69
def graph
  self.class.graph
end
label() click to toggle source
# File lib/redgraph/node_model.rb, line 73
def label
  self.class.label
end
to_node() click to toggle source
# File lib/redgraph/node_model.rb, line 89
def to_node
  props = attributes.except(:id).merge(_type: self.class.name)
  Redgraph::Node.new(id: id, label: label, properties: props)
end