Sha256: cd697867bac8f8c72e16091708ec878106e60f84d9db530a7ede4b53033320e1

Contents?: true

Size: 1.05 KB

Versions: 1

Compression:

Stored size: 1.05 KB

Contents

class Role < ActiveRecord::Base
  belongs_to :user
  validates :name,
            presence:   true,
            uniqueness: { scope: :user_id },
            inclusion:  { in: proc { Role.roles.map(&:name) } }

  class << self
    def define(name, description, default = false)
      if roles.map(&:name).include?(name.to_s)
        raise ArgumentError, "Tried to define role :#{role}, " \
          "but a role by that name already exists"
      else
        roles << OpenStruct.new(
          name: name.to_s,
          description: description,
          default: default
        )
      end
    end

    def roles
      @roles ||= default_roles
    end

    def names
      all.map(&:name)
    end

    protected

    def default_roles
      [
        OpenStruct.new(
          name: "users", description: "Can manage users", default: false
        ),
        OpenStruct.new(
          name: "pages", description: "Can manage pages", default: true
        )
      ]
    end
  end

  def name=(new_name)
    super(new_name.to_s)
  end

  def to_s
    name.humanize
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
pages_core-3.5.1 app/models/role.rb