mirror of
https://github.com/Fishwaldo/role_model.git
synced 2025-03-15 11:32:04 +00:00
Added support for dynamic matchers
This commit is contained in:
parent
7f55772f21
commit
39caec8984
2 changed files with 42 additions and 0 deletions
|
@ -58,6 +58,22 @@ module RoleModel
|
|||
self.send("#{self.class.roles_attribute_name}") == self.class.mask_for(*roles)
|
||||
end
|
||||
alias_method :is_exactly?, :has_only_roles?
|
||||
|
||||
# Dynamic matchers:
|
||||
# #is_<:role>?
|
||||
# #<:role>?
|
||||
#
|
||||
# Defines new methods which call #is?(:role)
|
||||
def method_missing(name, *args, &block)
|
||||
if name =~ /^(?:is_)?(.+)\?$/
|
||||
role = $1.to_sym
|
||||
self.class.instance_eval do
|
||||
define_method(name.to_sym) { is? role }
|
||||
end
|
||||
return self.send(name)
|
||||
end
|
||||
super
|
||||
end
|
||||
|
||||
end
|
||||
end
|
||||
|
|
|
@ -296,6 +296,32 @@ describe RoleModel do
|
|||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe "dynamically query for an individual role" do
|
||||
subject { model_class.new }
|
||||
|
||||
it "should return true when the given role was assigned" do
|
||||
subject.roles = :foo
|
||||
subject.is_foo?.should be_true
|
||||
subject.foo?.should be_true
|
||||
end
|
||||
|
||||
it "should return false when the given role was not assigned" do
|
||||
subject.roles = :bar
|
||||
subject.is_foo?.should be_false
|
||||
subject.foo?.should be_false
|
||||
end
|
||||
|
||||
it "should return false when no role was assigned" do
|
||||
subject.is_foo?.should be_false
|
||||
subject.bar?.should be_false
|
||||
end
|
||||
|
||||
it "should return false when asked for an undefined role" do
|
||||
subject.baz?.should be_false
|
||||
subject.is_baz?.should be_false
|
||||
end
|
||||
end
|
||||
|
||||
context "query for multiple roles" do
|
||||
[:has_any_role?, :is_any_of?, :has_role?].each do |check_role_assignment_method|
|
||||
|
|
Loading…
Add table
Reference in a new issue