Class: Policy

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

Defined Under Namespace

Modules: ModelAdapter Classes: Error, Proxy

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model:, user:) ⇒ Policy

Returns a new instance of Policy.



4
5
6
7
# File 'lib/clean-policy/base.rb', line 4

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

Instance Attribute Details

#actionObject (readonly)

Returns the value of attribute action.



2
3
4
# File 'lib/clean-policy/base.rb', line 2

def action
  @action
end

#modelObject (readonly)

Returns the value of attribute model.



2
3
4
# File 'lib/clean-policy/base.rb', line 2

def model
  @model
end

#userObject (readonly)

Returns the value of attribute user.



2
3
4
# File 'lib/clean-policy/base.rb', line 2

def user
  @user
end

Instance Method Details

#canObject



25
26
27
# File 'lib/clean-policy/base.rb', line 25

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)


11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/clean-policy/base.rb', line 11

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