Sha256: 18c7ffa9241a9b73521c939c58d4c79158707380e31d2679f22d994a6f2f4317

Contents?: true

Size: 1.59 KB

Versions: 6

Compression:

Stored size: 1.59 KB

Contents

module Saucy
  module Project
    extend ActiveSupport::Concern

    included do
      belongs_to :account
      has_many :permissions, :dependent => :destroy
      has_many :users, :through => :permissions

      validates_presence_of :account_id

      after_create :assign_default_memberships
      after_save :update_memberships

      # We have to define this here instead of mixing it in,
      # because ActiveRecord does the same
      def user_ids=(new_user_ids)
        @new_user_ids = new_user_ids.reject { |user_id| user_id.blank? }
      end
    end

    module ClassMethods
      def visible_to(user)
        where(['projects.id IN(?)', user.project_ids])
      end

      def by_name
        order("projects.name")
      end
    end

    module InstanceMethods
      def has_member?(user)
        permissions.
          joins(:membership).
          exists?(:memberships => { :user_id => user.id })
      end

      private

      def assign_default_memberships
        account.memberships.where(:admin => true).each do |membership|
          self.permissions.create(:membership => membership)
        end
      end

      def update_memberships
        if @new_user_ids
          removed_user_ids = self.user_ids - @new_user_ids
          added_user_ids = @new_user_ids - self.user_ids

          permissions.where(:user_id => removed_user_ids).destroy_all
          added_user_ids.each do |added_user_id|
            membership =
              account.memberships.where(:user_id => added_user_id).first
            permissions.create!(:membership => membership)
          end
        end
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
saucy-0.1.9 lib/saucy/project.rb
saucy-0.1.8 lib/saucy/project.rb
saucy-0.1.7 lib/saucy/project.rb
saucy-0.1.6 lib/saucy/project.rb
saucy-0.1.5 lib/saucy/project.rb
saucy-0.1.4 lib/saucy/project.rb