Skip to content

Commit

Permalink
Undefine dynamic methods on removing last role.
Browse files Browse the repository at this point in the history
  • Loading branch information
sampatbadhe committed Feb 27, 2023
1 parent 0cf293f commit 3e75de8
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 8 deletions.
26 changes: 19 additions & 7 deletions lib/rolify/dynamic.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,26 @@
module Rolify
module Dynamic
def define_dynamic_method(role_name, resource)
class_eval do
define_method("is_#{role_name}?".to_sym) do
has_role?("#{role_name}")
end if !method_defined?("is_#{role_name}?".to_sym) && self.adapter.where_strict(self.role_class, name: role_name).exists?
class_eval do
if self.adapter.where_strict(self.role_class, name: role_name).exists?
if !method_defined?("is_#{role_name}?".to_sym)
define_method("is_#{role_name}?".to_sym) do
has_role?("#{role_name}")
end
end
else
undef_method("is_#{role_name}?".to_sym) if method_defined?("is_#{role_name}?".to_sym)
end

define_method("is_#{role_name}_of?".to_sym) do |arg|
has_role?("#{role_name}", arg)
end if !method_defined?("is_#{role_name}_of?".to_sym) && resource && self.adapter.where_strict(self.role_class, name: role_name, resource: resource).exists?
if resource && self.adapter.where_strict(self.role_class, name: role_name, resource: resource).exists?
if !method_defined?("is_#{role_name}_of?".to_sym)
define_method("is_#{role_name}_of?".to_sym) do |arg|
has_role?("#{role_name}", arg)
end
end
else
undef_method("is_#{role_name}_of?".to_sym) if method_defined?("is_#{role_name}_of?".to_sym)
end
end
end
end
Expand Down
3 changes: 2 additions & 1 deletion lib/rolify/role.rb
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ def only_has_role?(role_name, resource = nil)

def remove_role(role_name, resource = nil)
self.class.adapter.remove(self, role_name.to_s, resource)
self.class.define_dynamic_method(role_name, resource) if Rolify.dynamic_shortcuts
end

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

0 comments on commit 3e75de8

Please sign in to comment.