Class: Policy

Inherits:
Object show all
Defined in:
lib/clean-policy/base.rb,
lib/clean-policy/error.rb,
lib/clean-policy/proxy.rb

Overview

true / false @model.can.write?

raise error or return true @model.can.write!

redirect on error or return true @model.can.write! { redirect_to ‘/login’ }

Defined Under Namespace

Classes: Error, Proxy

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model:, user:) ⇒ Policy

Returns a new instance of Policy.



12
13
14
15
# File 'lib/clean-policy/base.rb', line 12

def initialize model:, user:
  @model = model
  @user  = user
end

Instance Attribute Details

#actionObject (readonly)

Returns the value of attribute action.



10
11
12
# File 'lib/clean-policy/base.rb', line 10

def action
  @action
end

#modelObject (readonly)

Returns the value of attribute model.



10
11
12
# File 'lib/clean-policy/base.rb', line 10

def model
  @model
end

#userObject (readonly)

Returns the value of attribute user.



10
11
12
# File 'lib/clean-policy/base.rb', line 10

def user
  @user
end

Instance Method Details

#before(action) ⇒ Object



58
59
60
# File 'lib/clean-policy/base.rb', line 58

def before action
  false
end

#call(*args, &block) ⇒ Object

call has to be isolated because specific of error handling



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/clean-policy/base.rb', line 34

def call *args, &block
  raise Error.new 'User is not defined' unless @user

  return true if before(@action)
  return true if send(@action, *args)
  raise Error.new('Access disabled in policy')
rescue Policy::Error => e
  error = e.message
  error += " - #{self.class}.#{@action}" if defined?(Lux) && Lux.config(:dump_errors)

  if block
    block.call(error)
    false
  else
    raise Policy::Error, error
  end
end

#canObject



52
53
54
# File 'lib/clean-policy/base.rb', line 52

def can
  Proxy.new self
end

#can?(action, *args, &block) ⇒ Boolean

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

Returns:

  • (Boolean)

Raises:

  • (RuntimeError)


19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/clean-policy/base.rb', line 19

def can? action, *args, &block
  @action = action
    .to_s
    .gsub(/[^\w+]/, '')
    .concat('?')
    .to_sym

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

  call *args, &block
end

#error(message) ⇒ Object

Raises:



62
63
64
# File 'lib/clean-policy/base.rb', line 62

def error message
  raise Policy::Error.new(message)
end