Sha256: d5daef7e233db3a3f5e050f73d80cfd053f1a72b9edaad99653ba02ea498a7b7

Contents?: true

Size: 1.91 KB

Versions: 1

Compression:

Stored size: 1.91 KB

Contents

module Klastera::Concerns::ClusterUser
  extend ActiveSupport::Concern

  included do
    self.table_name = 'cluster_users'

    belongs_to :user
    belongs_to :cluster

    validates :cluster_id, presence: true

    scope :of, -> (user,organization) {
      Rails.logger.warn("DON'T USE THIS SCOPE DIRECTLY: Use ::ClusterUser.get_from class method instead!")
      includes(:cluster).where(user_id: user, "clusters.organization_id": organization)
    }
  end
  
  module ClassMethods

    ##
    # Returns a hash with the users with cluster relation
    #
    def get_user_clusters_from(organization)
      users_hash = {}
      organization_cluster_ids = ::Cluster.of(organization).map(&:id)
      ::ClusterUser.includes(:user).where(cluster_id: organization_cluster_ids).each do |cluster|
        user_id = cluster.try(:user).try(:id) || :uncluster
        users_hash[user_id] ||= [];
        users_hash[user_id] << cluster.id
      end
      users_hash
    end

    ##
     # Returns a Cluster::ActiveRecord_Relation
     #
     ##
    def get_clusters_from(user,organization)
      clusters = []
      unless user.can_admin_clusters?
        # We could return cu.clusters but you may quering this result and a array can't handle order, where and etc.
        # So we take only the cluster_ids and perfome a new search in order to get a Cluster::ActiveRecord_Relation 
        # like the else block.
        # TODO: resolve it without quering twice
        clusters_id = ::ClusterUser.of(user,organization).map(&:cluster_id)
        clusters = ::Cluster.where(id: clusters_id)
        # Add a empty cluster instance to handle models without a cluster assignation. Only for use and show modes
        if organization.optional_mode?
          clusters << ::Cluster.new({nid: :without_cluster, name: I18n.t('klastera.without_cluster')})
        end
      else
        clusters = ::Cluster.of(organization)
      end
      clusters
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
klastera-1.1.6.1 app/models/klastera/concerns/cluster_user.rb