Sha256: cd65fc7f0f34dd45e05bfb99fe4e7ea3aac113d52fb6dcdf4c68dca9d1fd9fbe

Contents?: true

Size: 1.82 KB

Versions: 9

Compression:

Stored size: 1.82 KB

Contents

# lib/apache_age/validators/unique_edge.rb

# Usage (within an Age Model)
# validates_with(
#   ApacheAge::Validators::UniqueEdge,
#   attributes: [:start_id, :employee_role, :end_id]
# )

module ApacheAge
  module Validators
    class UniqueEdge < ActiveModel::Validator
      def validate(record)
        allowed_keys = record.age_properties.keys
        attributes = options[:attributes] || []

        edge_attribs =
          attributes
          .map { |attr| [attr, record.send(attr)] }.to_h
          .symbolize_keys
          .slice(*allowed_keys)

        possible_end_keys = [:end_id, 'end_id', :end_node, 'end_node']
        end_query =
          if possible_end_keys.any? { |key| attributes.include?(key) }
            end_query = query_node(record.end_node)
            edge_attribs[:end_id] = end_query&.id
            end_query
          end

        possible_start_keys = [:start_id, 'start_id', :start_node, 'start_node']
        start_query =
          if possible_start_keys.any? { |key| attributes.include?(key) }
            start_query = query_node(record.start_node)
            edge_attribs[:start_id] = start_query&.id
            start_query
          end
        return if attributes.blank? && (end_query.blank? || start_query.blank?)

        query = record.class.find_by(edge_attribs.compact)
        return if query.blank? || (query.id == record.id)

        record.errors.add(:base, 'record not unique')
        record.errors.add(:end_node, 'node combination not unique')
        record.errors.add(:start_node, 'node combination not unique')
        attributes.each { record.errors.add(_1, 'prpoerty combination not unique') }
      end

      private

      def query_node(node)
        return nil if node.blank?

        node.persisted? ? node.class.find(node.id) : node.class.find_by(node.age_properties)
      end
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
rails_age-0.6.4 lib/apache_age/validators/unique_edge.rb
rails_age-0.6.3 lib/apache_age/validators/unique_edge.rb
rails_age-0.6.2 lib/apache_age/validators/unique_edge.rb
rails_age-0.6.1 lib/apache_age/validators/unique_edge.rb
rails_age-0.6.0 lib/apache_age/validators/unique_edge.rb
rails_age-0.5.3 lib/apache_age/validators/unique_edge.rb
rails_age-0.5.2 lib/apache_age/validators/unique_edge.rb
rails_age-0.5.1 lib/apache_age/validators/unique_edge.rb
rails_age-0.5.0 lib/apache_age/validators/unique_edge.rb