Created
May 2, 2013 01:51
-
-
Save plukevdh/5499688 to your computer and use it in GitHub Desktop.
User Ability DSL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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