Sha256: 2446fa33920fd505e5838d8e61d330b1b5ef2feb0a1049f60850d0596a547400

Contents?: true

Size: 1.29 KB

Versions: 15

Compression:

Stored size: 1.29 KB

Contents

module Spotlight
  ##
  # Exhibit authorization roles
  class Role < ActiveRecord::Base
    ROLES = %w(admin curator).freeze
    belongs_to :resource, polymorphic: true
    belongs_to :user, class_name: Spotlight::Engine.config.user_class, autosave: true
    validates :role, inclusion: { in: ROLES }
    validates :user_key, presence: true
    validate :user_must_exist, if: -> { user_key.present? }
    validate :user_must_be_unique, if: :user

    def user_key
      if user
        @user_key = user.user_key
      else
        @user_key
      end
    end

    # setting user key causes the user to get set
    def user_key=(key)
      @user_key = key
      self.user ||= Spotlight::Engine.user_class.find_by_user_key(key)
      user.user_key = key if user
    end

    protected

    def user_must_exist
      return if user.present?

      self.user ||= Spotlight::Engine.user_class.invite!(email: user_key, skip_invitation: true)
    end

    # This is just like
    #    validates :user, uniqueness: { scope: :exhibit}
    # but it puts the error message on the user_key instead of user so that the form will render correctly
    def user_must_be_unique
      errors.add(:user_key, 'already a member of this exhibit') if Spotlight::Role.where(resource: resource, user: user).where.not(id: id).any?
    end
  end
end

Version data entries

15 entries across 15 versions & 1 rubygems

Version Path
blacklight-spotlight-0.34.1 app/models/spotlight/role.rb
blacklight-spotlight-0.34.0 app/models/spotlight/role.rb
blacklight-spotlight-0.33.3 app/models/spotlight/role.rb
blacklight-spotlight-0.33.2 app/models/spotlight/role.rb
blacklight-spotlight-0.33.1 app/models/spotlight/role.rb
blacklight-spotlight-0.33.0 app/models/spotlight/role.rb
blacklight-spotlight-0.32.0 app/models/spotlight/role.rb
blacklight-spotlight-0.31.0 app/models/spotlight/role.rb
blacklight-spotlight-0.30.0 app/models/spotlight/role.rb
blacklight-spotlight-0.29.1 app/models/spotlight/role.rb
blacklight-spotlight-0.29.0 app/models/spotlight/role.rb
blacklight-spotlight-0.28.3 app/models/spotlight/role.rb
blacklight-spotlight-0.28.2 app/models/spotlight/role.rb
blacklight-spotlight-0.28.1 app/models/spotlight/role.rb
blacklight-spotlight-0.28.0 app/models/spotlight/role.rb