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
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
# File 'lib/simple_can.rb', line 49 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 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
79 80 81 |
# File 'lib/simple_can.rb', line 79 def capability Thread.current[THREAD_VAR] end |
#capability=(role) ⇒ Object
74 75 76 77 |
# File 'lib/simple_can.rb', line 74 def capability=(role) strategy_set! Thread.current[THREAD_VAR] = SimpleCan.strategy.to_capability(role) end |
#method_added(method) ⇒ Object
39 40 41 42 |
# File 'lib/simple_can.rb', line 39 def method_added(method) orig_method_added(method) add_method_to(self, method) end |
#singleton_method_added(method) ⇒ Object
44 45 46 47 |
# File 'lib/simple_can.rb', line 44 def singleton_method_added(method) orig_singleton_method_added(method) add_method_to((class << self; self; end), method) end |
#strategy_set! ⇒ Object
35 36 37 |
# File 'lib/simple_can.rb', line 35 def strategy_set! raise "strategy missing" if SimpleCan.strategy.nil? end |
#with_capability(role) ⇒ Object
83 84 85 86 87 88 |
# File 'lib/simple_can.rb', line 83 def with_capability(role) self.capability = role yield ensure self.capability = nil end |