Module: SimpleCan::ClassMethods
- Defined in:
- lib/simple_can.rb
Instance Method Summary collapse
- #add_method_to(scope, method) ⇒ Object
- #capability ⇒ Object
- #capability=(role) ⇒ Object
- #method_added(method) ⇒ Object
- #singleton_method_added(method) ⇒ Object
- #strategy_set! ⇒ Object
- #with_capability(role) ⇒ Object
Instance Method Details
#add_method_to(scope, method) ⇒ Object
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
# File 'lib/simple_can.rb', line 48 def add_method_to(scope, method) strategy_set! klass = self method = method.to_s role, name, do_raise = SimpleCan.strategy.roles.reduce(nil) do |acc, r| acc || method.match(/^#{r}_(.+(!)|.+)$/)&.captures&.unshift(r) end return if name.nil? scope.send(:define_method, name) do |*args, &blk| can = SimpleCan.strategy.test(role, klass.capability) if !can && !do_raise.nil? raise SimpleCan::Unauthorized, "unauthorized for #{name} with #{role}" elsif !can if respond_to?("fail_#{name}") return send("fail_#{name}") else return SimpleCan.strategy.fail(role, name) end else return send(method, *args, &blk) end end end |
#capability ⇒ Object
78 79 80 |
# File 'lib/simple_can.rb', line 78 def capability Thread.current[THREAD_VAR] end |
#capability=(role) ⇒ Object
73 74 75 76 |
# File 'lib/simple_can.rb', line 73 def capability=(role) strategy_set! Thread.current[THREAD_VAR] = SimpleCan.strategy.to_capability(role) end |
#method_added(method) ⇒ Object
38 39 40 41 |
# File 'lib/simple_can.rb', line 38 def method_added(method) orig_method_added(method) add_method_to(self, method) end |
#singleton_method_added(method) ⇒ Object
43 44 45 46 |
# File 'lib/simple_can.rb', line 43 def singleton_method_added(method) orig_singleton_method_added(method) add_method_to((class << self; self; end), method) end |
#strategy_set! ⇒ Object
34 35 36 |
# File 'lib/simple_can.rb', line 34 def strategy_set! raise "strategy missing" if SimpleCan.strategy.nil? end |
#with_capability(role) ⇒ Object
82 83 84 85 86 87 |
# File 'lib/simple_can.rb', line 82 def with_capability(role) self.capability = role yield ensure self.capability = nil end |