mirror of
https://github.com/Fishwaldo/role_model.git
synced 2025-03-15 11:32:04 +00:00
Predefine dynamic queries from valid roles
This commit is contained in:
parent
9f8c48b69e
commit
04d0674ff1
3 changed files with 31 additions and 19 deletions
|
@ -34,7 +34,22 @@ module RoleModel
|
|||
#
|
||||
# declare valid roles
|
||||
def roles(*roles)
|
||||
opts = roles.last.is_a?(Hash) ? roles.pop : {}
|
||||
self.valid_roles = roles.flatten.map(&:to_sym)
|
||||
self.define_dynamic_queries unless opts[:dynamic] == false
|
||||
end
|
||||
|
||||
# Defines dynamic queries for valid_roles:
|
||||
# #is_<:role>?
|
||||
# #<:role>?
|
||||
#
|
||||
# Defines new methods which call #is?(:role)
|
||||
def define_dynamic_queries
|
||||
valid_roles.each do |role|
|
||||
["#{role}?".to_sym, "is_#{role}?".to_sym].each do |method|
|
||||
define_method(method) { is? role }
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
|
|
@ -58,22 +58,6 @@ 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.to_s =~ /^(?: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
|
||||
|
|
|
@ -317,9 +317,22 @@ describe RoleModel do
|
|||
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
|
||||
it "should throw NoMethodError when asked for an undefined role" do
|
||||
lambda { subject.baz? }.should raise_error(NoMethodError)
|
||||
lambda { subject.is_baz? }.should raise_error(NoMethodError)
|
||||
end
|
||||
|
||||
it "should not define dynamic finders when opting out" do
|
||||
non_dynamic_klass = Class.new do
|
||||
attr_accessor :roles_mask
|
||||
attr_accessor :custom_roles_mask
|
||||
include RoleModel
|
||||
roles :foo, :bar, :third, :dynamic => false
|
||||
end
|
||||
|
||||
model = non_dynamic_klass.new
|
||||
lambda { model.is_foo? }.should raise_error(NoMethodError)
|
||||
lambda { model.bar? }.should raise_error(NoMethodError)
|
||||
end
|
||||
end
|
||||
|
||||
|
|
Loading…
Add table
Reference in a new issue