Created
June 29, 2011 18:51
-
-
Save timothyklim/1054581 to your computer and use it in GitHub Desktop.
Group
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 Group | |
include DataMapper::Resource | |
property :id, Serial | |
property :title, String, unique: true, length: 1..20 | |
property :rules, String | |
SUPPORT_MODELS = %w[account offering city country] | |
SUPPORT_ACTIONS = %w[read create destroy edit] | |
def can? action, model | |
action = action.to_s.downcase | |
if model.is_a? String or model.is_a? Symbol | |
model = model.to_s.downcase | |
else | |
if model.respond_to? :name and model.is_a? Class | |
model = model.name.to_s.downcase | |
else | |
model = model.class.name.to_s.downcase | |
end | |
end | |
return false unless SUPPORT_MODELS.include?(model) | |
return false unless SUPPORT_ACTIONS.include?(action) | |
rules_hash[model] ? rules_hash[model].include?(action) : false | |
end | |
def method_missing name, *args | |
if name =~ /^role_([a-z]+)_([a-z]+)(?:(\=))?$/ | |
if SUPPORT_MODELS.include?($1) and SUPPORT_ACTIONS.include?($2) | |
_hash = rules_hash | |
if $3.nil? | |
return false if _hash[$1].nil? | |
_hash[$1].include?($2) | |
else | |
if args.first | |
_hash[$1] ||= [] | |
_hash[$1] << $2 unless _hash[$1].include?($2) | |
else | |
_hash[$1].delete $2 | |
end | |
self.rules_hash = _hash | |
end | |
else | |
super | |
end | |
else | |
super | |
end | |
end | |
private | |
def rules_hash | |
if self.rules | |
JSON::parse(self.rules) | |
else | |
{} | |
end | |
end | |
def rules_hash= hash | |
self.rules = hash.to_json | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment