Skip to content

Instantly share code, notes, and snippets.

@plukevdh
Created May 2, 2013 01:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save plukevdh/5499688 to your computer and use it in GitHub Desktop.
Save plukevdh/5499688 to your computer and use it in GitHub Desktop.
User Ability DSL
class User
module Ability
def self.included(klass)
klass.instance_eval do
def ability(role, abilities)
send :define_method, role.to_sym do
abilities
end
end
end
klass.class_eval do
def has_ability?(ability)
self.send(self.role.to_sym).include? ability
end
def abilities
self.send(self.role.to_sym)
end
end
end
FAKE_METHOD = /can_(.+)\?/
def method_missing(method, *args, &block)
if method =~ FAKE_METHOD
self.has_ability?(method[FAKE_METHOD, 1].to_sym)
else
super
end
end
end
end
class User
module Roles
# Available roles, in descending order of authorization
ROLES = [
:viewer,
:dev,
:qa,
:lead,
:manager,
:admin
]
DEFAULT = ROLES.first
def self.included(klass)
ROLES.each do |role|
klass.send :define_method, "make_#{role}".to_sym do
update_attribute :role, role.to_s
end
klass.send :define_method, "#{role}?".to_sym do
self.role.to_sym == role.to_sym
end
end
end
end
end
class User
include Roles
include Ability
ability :viewer, []
ability :qa, [:reject, :accept, :start_test]
ability :dev, [:start, :finish]
ability :manager, [:review, :release, :commit, :backlog]
ability :lead, [:commit, :backlog]
ability :admin, [:reject, :accept, :start_test, :start, :finish, :review, :release, :commit, :backlog]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment