lib/redgraph/node_model.rb in redgraph-0.1.4 vs lib/redgraph/node_model.rb in redgraph-0.2.0
- old
+ new
@@ -1,6 +1,7 @@
# frozen_string_literal: true
+require_relative 'node_model/class_methods'
module Redgraph
# This mixin allows you to use an interface similar to ActiveRecord
#
# class Actor
@@ -14,17 +15,21 @@
# 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.
+ #
module NodeModel
extend ActiveSupport::Concern
- included do
+ included do |base|
@attribute_names = [:id]
attr_accessor :id
+ attr_accessor :_type
class << self
attr_reader :attribute_names
attr_accessor :graph
@@ -41,61 +46,12 @@
subclass.instance_variable_set(:@graph, @graph.dup)
end
end
end
- class_methods do
- # Returns an array of nodes. Options:
- #
- # - properties: filter by properties
- # - order: node.name ASC, node.year DESC
- # - limit: number of items
- # - skip: items offset (useful for pagination)
- #
- def all(properties: nil, limit: nil, skip: nil, order: nil)
- graph.nodes(label: label, properties: properties,
- limit: limit, skip: skip, order: nil).map do |node|
- new(id: node.id, **node.properties)
- end
- end
-
- # Returns the number of nodes with the current label. Options:
- #
- # - properties: filter by properties
- #
- def count(properties: nil)
- graph.count_nodes(label: label, properties: properties)
- end
-
- # Finds a node by id. Returns nil if not found
- #
- def find(id)
- node = graph.find_node_by_id(id)
- return unless node
- new(id: node.id, **node.properties)
- end
-
- # Sets the label for this class of nodes. If missing it will be computed from the class name
- def label=(x)
- @label = x
- end
-
- # Current label
- #
- def label
- @label ||= default_label
- end
-
- private
-
- def default_label
- name.demodulize.underscore
- end
- end
-
def initialize(**args)
- absent_attributes = args.keys.map(&:to_sym) - self.class.attribute_names
+ absent_attributes = args.keys.map(&:to_sym) - self.class.attribute_names - [:_type]
if absent_attributes.any?
raise ArgumentError, "Unknown attribute #{absent_attributes}"
end
@@ -147,10 +103,17 @@
edge = Edge.new(type: type, src: to_node, dest: node.to_node, properties: properties)
allow_duplicates ? graph.add_edge(edge) : graph.merge_edge(edge)
end
def to_node
- Redgraph::Node.new(id: id, label: label, properties: attributes.except(:id))
+ props = attributes.except(:id).merge(_type: self.class.name)
+ Redgraph::Node.new(id: id, label: label, properties: props)
+ end
+
+ # Converts a Node object into NodeModel
+ #
+ def reify_from_node(node)
+ self.class.reify_from_node(node)
end
def ==(other)
attributes == other.attributes && id == other.id
end