Class: Policy

Inherits:
Object show all
Defined in:
lib/common/policy.rb

Overview

block will capture error message and be triggered only if error is present User.can?(:login) { |msg| http_error 401, “Err: #msg”.red; return ‘no access’ }

Instance Method Summary collapse

Constructor Details

#initialize(hash) ⇒ Policy

Returns a new instance of Policy.



12
13
14
15
16
# File 'lib/common/policy.rb', line 12

def initialize hash
  for k, v in hash
    instance_variable_set "@#{k}", v
  end
end

Instance Method Details

#before(action) ⇒ Object



46
47
48
# File 'lib/common/policy.rb', line 46

def before action
  false
end

#call(&block) ⇒ Object

call has to be isolated because specific of error handling



32
33
34
35
36
37
38
39
40
41
42
# File 'lib/common/policy.rb', line 32

def call &block
  return true if before(@action)
  return true if send(@action)
  raise UnauthorizedError, 'Access disabled in policy'
 rescue UnauthorizedError
  error = $!.message
  error += " - #{self.class}.#{@action}" if Lux.config(:show_server_errors)
  raise UnauthorizedError, error unless block
  block.call(error)
  false
end

#can?(action, &block) ⇒ Boolean

pass block if you want to handle errors yourself return true if false if block is passed

Returns:

  • (Boolean)

Raises:

  • (RuntimeError)


20
21
22
23
24
25
26
27
28
29
# File 'lib/common/policy.rb', line 20

def can? action, &block
  @action = action.to_s.sub('?','') + '?'
  @action = @action.to_sym

  # pre check
  raise RuntimeError, 'Method name not allowed' if %w(can).index(@action)
  raise NoMethodError, %[Policy check "#{action}" not found in #{self.class}] unless respond_to?(@action)

  call &block
end

#error(message) ⇒ Object

Raises:

  • (UnauthorizedError)


50
51
52
# File 'lib/common/policy.rb', line 50

def error message
  raise UnauthorizedError, message
end