Skip to content

Instantly share code, notes, and snippets.

@jonathanccalixto
Created September 9, 2016 13:50
Show Gist options
  • Save jonathanccalixto/1d6182dd6bf6ee8a53df449820d48ec0 to your computer and use it in GitHub Desktop.
Save jonathanccalixto/1d6182dd6bf6ee8a53df449820d48ec0 to your computer and use it in GitHub Desktop.
class CreateProfiles < ActiveRecord::Migration
def change
create_table :profiles do |t|
t.string :name
t.timestamps null: false
t.index :name
end
end
end
class CreatePermissions < ActiveRecord::Migration
def change
create_table :permissions do |t|
t.references :profile, index: true, foreign_key: true
t.string :role, index: true
t.boolean :can_create, default: false
t.boolean :can_read, default: false
t.boolean :can_update, default: false
t.boolean :can_delete, default: false
t.timestamps null: false
end
end
end
class ApplicationPolicy
class Scope
attr_reader :user, :scope
def initialize(user, scope)
@user = user
@scope = scope
end
def resolve
scope
end
end
attr_reader :user, :record, :role_name
def initialize(user, record)
@user = user
@record = record
@role_name = "#{self.class}".sub(/Policy/, '').tableize.singularize
end
def index?
can_list?
end
def show?
can_show?
end
def create?
can_create?
end
def new?
create?
end
def update?
can_update?
end
def edit?
update?
end
def destroy?
can_destroy?
end
def scope
Pundit.policy_scope!(user, record.class)
end
def permission
user.permission(role_name) || Permission.new
end
protected
def can_list?
permission.can_read?
end
def can_show?
scope.where(:id => record.id).exists? && permission.can_read?
end
def can_create?
permission.can_create?
end
def can_update?
permission.can_update?
end
def can_destroy?
permission.can_delete?
end
end
roles:
- company
- user
- profile
# This file can be in any of the following folders:
# - config/initializers
# - app/models
# - app/enumerations
# - app/<<any other folder>>
class SystemRoles
def self.roles
new.to_h
end
def self.role(key)
self.roles[key.to_sym] if key
end
def to_a(loader = YAML)
@roles ||= loader.load(File.open("#{Rails.root}/config/roles.yml"))["roles"].sort.map(&:to_sym)
end
def to_h
to_a.inject([]) do |hash, role|
hash << [
role,
[
I18n.t("roles.#{role}", default: '').strip,
I18n.t("activerecord.models.#{role}", count: :many, default: '').strip,
I18n.t("activemodel.models.#{role}", count: :many, default: '').strip,
role.to_s.strip
].reject(&:blank?).first
]
hash
end.sort{ |a1, a2| a1.second <=> a2.second }.to_h
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment