Skip to content

Commit 3e75de8

Browse files
committed
Undefine dynamic methods on removing last role.
1 parent 0cf293f commit 3e75de8

File tree

2 files changed

+21
-8
lines changed

2 files changed

+21
-8
lines changed

lib/rolify/dynamic.rb

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,26 @@
33
module Rolify
44
module Dynamic
55
def define_dynamic_method(role_name, resource)
6-
class_eval do
7-
define_method("is_#{role_name}?".to_sym) do
8-
has_role?("#{role_name}")
9-
end if !method_defined?("is_#{role_name}?".to_sym) && self.adapter.where_strict(self.role_class, name: role_name).exists?
6+
class_eval do
7+
if self.adapter.where_strict(self.role_class, name: role_name).exists?
8+
if !method_defined?("is_#{role_name}?".to_sym)
9+
define_method("is_#{role_name}?".to_sym) do
10+
has_role?("#{role_name}")
11+
end
12+
end
13+
else
14+
undef_method("is_#{role_name}?".to_sym) if method_defined?("is_#{role_name}?".to_sym)
15+
end
1016

11-
define_method("is_#{role_name}_of?".to_sym) do |arg|
12-
has_role?("#{role_name}", arg)
13-
end if !method_defined?("is_#{role_name}_of?".to_sym) && resource && self.adapter.where_strict(self.role_class, name: role_name, resource: resource).exists?
17+
if resource && self.adapter.where_strict(self.role_class, name: role_name, resource: resource).exists?
18+
if !method_defined?("is_#{role_name}_of?".to_sym)
19+
define_method("is_#{role_name}_of?".to_sym) do |arg|
20+
has_role?("#{role_name}", arg)
21+
end
22+
end
23+
else
24+
undef_method("is_#{role_name}_of?".to_sym) if method_defined?("is_#{role_name}_of?".to_sym)
25+
end
1426
end
1527
end
1628
end

lib/rolify/role.rb

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@ def only_has_role?(role_name, resource = nil)
8080

8181
def remove_role(role_name, resource = nil)
8282
self.class.adapter.remove(self, role_name.to_s, resource)
83+
self.class.define_dynamic_method(role_name, resource) if Rolify.dynamic_shortcuts
8384
end
8485

8586
alias_method :revoke, :remove_role
@@ -101,7 +102,7 @@ def method_missing(method, *args, &block)
101102
def respond_to?(method, include_private = false)
102103
if Rolify.dynamic_shortcuts && (method.to_s.match(/^is_(\w+)_of[?]$/) || method.to_s.match(/^is_(\w+)[?]$/))
103104
query = self.class.role_class.where(:name => $1)
104-
if query
105+
if query.exists?
105106
query = self.class.adapter.exists?(query, :resource_type) if method.to_s.match(/^is_(\w+)_of[?]$/)
106107
return query.count > 0
107108
end

0 commit comments

Comments
 (0)