module Klastera::Concerns::Cluster extend ActiveSupport::Concern # 'included do' causes the included code to be evaluated in the # context where it is included (cluster.rb), rather than being # executed in the module's context (klastera/concerns/models/cluster). included do self.table_name = 'clusters' attr_reader :last_record MODES = [ :suborganization, :required_filter, :optional_filter ].freeze default_scope { includes(:organization).order(id: :desc) } belongs_to :organization, class_name: Klastera.organization_class scope :all_clusters_of, lambda { |organization,except_ids=[]| g=where(organization: organization) g.where.not(id: except_ids) unless except_ids.blank? } validates :name, presence: true validates :nid, presence: true validates :organization_id, presence: true validates_uniqueness_of :nid, scope: [:nid, :organization_id] before_destroy do |record| self.can_transfer_and_destroy? end def siblings self.class.all_clusters_of(self.organization,[self.id]) end def is_the_last_record_in_suborganization_mode? self.organization.suborganization_mode? && self.siblings.blank? end def required_transfer? self.organization.suborganization_mode? end def has_related_entities_using_it? ::Cluster.total_records_assign_to(self) > 0 end def can_transfer_and_destroy? can_destroy = true if is_the_last_record_in_suborganization_mode? errors.add(:last_record, I18n.t('klastera.messages.cant_delete_the_last_record_in_suborganization_mode')) can_destroy = false end can_destroy end end module ClassMethods def related_entities(attr_needed: :class_name, macro: :has_many) ::Cluster.reflections.map do |association_name, reflection| reflection.send(attr_needed) if reflection.macro == macro end.compact end def total_records_assign_to(cluster_instance) related_entities(attr_needed: :name).inject(0) do |total, association_name| entity = cluster_instance.send(association_name) if entity.respond_to?(:cluster_id) total+=entity.where(cluster_id: cluster_instance.id).count end total end end def modes_as_strings ::Cluster::MODES.map{|m|m.to_s} end end end