Sha256: 084bcf103537f313158f0fbd36ccb89d92803aa3f64a387e9b183e4a3c510f53

Contents?: true

Size: 1.99 KB

Versions: 10

Compression:

Stored size: 1.99 KB

Contents

module Pageflow
  # ActiveRecord related functionality of the Pageflow users.
  module UserMixin
    extend ActiveSupport::Concern

    NON_ADMIN_ROLES = ['editor', 'account_manager']
    ROLES = NON_ADMIN_ROLES + ['admin']

    include Suspendable

    included do
      belongs_to :account, :class_name => 'Pageflow::Account'

      has_many :memberships, :dependent => :destroy, :class_name => 'Pageflow::Membership'
      has_many :entries, :through => :memberships, :class_name => 'Pageflow::Entry'

      has_many :revisions, :class_name => 'Pageflow::Revision', :foreign_key => :creator_id

      validates :first_name, :last_name, :presence => true
      validates :role, :inclusion => ROLES
      validates :account, :presence => true

      scope :admins, -> { where(:role => 'admin') }
      scope :account_managers, -> { where(:role => 'account_manager') }
      scope :editors, -> { where(:role => 'editor') }
    end

    def admin?
      role == 'admin'
    end

    def account_manager?
      role == 'account_manager'
    end

    def full_name
      [first_name, last_name] * " "
    end

    def formal_name
      [last_name, first_name] * ", "
    end

    def locale
      super.presence || I18n.default_locale
    end

    def update_with_password(attributes)
      if needs_password?(attributes)
        super(attributes)
      else
        # remove the virtual current_password attribute update_without_password
        # doesn't know how to ignore it
        update_without_password(attributes.except(:current_password))
      end
    end

    def destroy_with_password(password)
      if valid_password?(password)
        destroy
        true
      else
        self.errors.add(:current_password, password.blank? ? :blank : :invalid)
        false
      end
    end

    module ClassMethods
      def roles_accessible_by(ability)
        ability.can?(:read, Account) ? ROLES : NON_ADMIN_ROLES
      end
    end

    private

    def needs_password?(attributes)
      attributes[:password].present?
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
pageflow-0.10.0 lib/pageflow/user_mixin.rb
pageflow-0.9.2 lib/pageflow/user_mixin.rb
pageflow-0.9.1 lib/pageflow/user_mixin.rb
pageflow-0.9.0 lib/pageflow/user_mixin.rb
pageflow-0.8.2 lib/pageflow/user_mixin.rb
pageflow-0.8.1 lib/pageflow/user_mixin.rb
pageflow-0.8.0 lib/pageflow/user_mixin.rb
pageflow-0.7.2 lib/pageflow/user_mixin.rb
pageflow-0.7.1 lib/pageflow/user_mixin.rb
pageflow-0.7.0 lib/pageflow/user_mixin.rb