lib/neo4j/active_node/labels.rb in neo4j-3.0.0.alpha.11 vs lib/neo4j/active_node/labels.rb in neo4j-3.0.0.rc.2

- old
+ new

@@ -7,10 +7,11 @@ extend ActiveSupport::Concern WRAPPED_CLASSES = [] class InvalidQueryError < StandardError; end class RecordNotFound < StandardError; end + class InvalidParameterError < StandardError; end # @return the labels # @see Neo4j-core def labels @_persisted_obj.labels @@ -69,18 +70,39 @@ self.query_as(:n).limit(1).order('ID(n)').pluck(:n).first end # Returns the last node of this class, sorted by ID. Note that this may not be the first node created since Neo4j recycles IDs. def last - self.query_as(:n).order('ID(n) DESC').limit(1).pluck(:n).first + self.query_as(:n).limit(1).order('ID(n) DESC').pluck(:n).first end # @return [Fixnum] number of nodes of this class - def count - self.query_as(:n).return("count(n) AS count").first.count + def count(distinct = nil) + raise(InvalidParameterError, ':count accepts `distinct` or nil as a parameter') unless distinct.nil? || distinct == :distinct + q = distinct.nil? ? "n" : "DISTINCT n" + self.query_as(:n).return("count(#{q}) AS count").first.count end + alias_method :size, :count + alias_method :length, :count + def empty? + !self.exists? + end + alias_method :blank?, :empty? + + def include?(other) + raise(InvalidParameterError, ':include? only accepts nodes') unless other.respond_to?(:neo_id) + self.query_as(:n).where("ID(n) = #{other.neo_id}").return("count(n) AS count").first.count > 0 + end + + def exists?(node_id=nil) + raise(InvalidParameterError, ':exists? only accepts neo_ids') unless node_id.is_a?(Integer) || node_id.nil? + start_q = self.query_as(:n) + end_q = node_id.nil? ? start_q : start_q.where("ID(n) = #{node_id}") + end_q.return("COUNT(n) AS count").first.count > 0 + end + # Returns the object with the specified neo4j id. # @param [String,Fixnum] id of node to find def find(id) raise "Unknown argument #{id.class} in find method (expected String or Fixnum)" if not [String, Fixnum].include?(id.class) find_by_id(id) @@ -145,20 +167,20 @@ label.create_constraint(property, constraints, session) end end def index?(index_def) - mapped_label.indexes[:property_keys].include?(index_def) + mapped_label.indexes[:property_keys].include?([index_def]) end # @return [Array{Symbol}] all the labels that this class has def mapped_label_names self.ancestors.find_all { |a| a.respond_to?(:mapped_label_name) }.map { |a| a.mapped_label_name.to_sym } end # @return [Symbol] the label that this class has which corresponds to a Ruby class def mapped_label_name - @_label_name || self.to_s.to_sym + @_label_name || (self.name.nil? ? object_id.to_s.to_sym : self.name.to_sym) end # @return [Neo4j::Label] the label for this class def mapped_label Neo4j::Label.create(mapped_label_name)