Class: DeclarativePolicy::Rule::Or

Inherits:
Base
  • Object
show all
Defined in:
lib/declarative_policy/rule.rb

Overview

Logical ‘or`. Mirrors And.

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#and, #inspect, make, #negate, #or

Constructor Details

#initialize(rules) ⇒ Or

Returns a new instance of Or.



235
236
237
# File 'lib/declarative_policy/rule.rb', line 235

def initialize(rules)
  @rules = rules
end

Instance Attribute Details

#rulesObject (readonly)

Returns the value of attribute rules.



233
234
235
# File 'lib/declarative_policy/rule.rb', line 233

def rules
  @rules
end

Instance Method Details

#cached_pass?(context) ⇒ Boolean

Returns:

  • (Boolean)


258
259
260
261
262
263
264
265
266
# File 'lib/declarative_policy/rule.rb', line 258

def cached_pass?(context)
  @rules.each do |rule|
    pass = rule.cached_pass?(context)

    return pass if pass.nil? || pass == true
  end

  false
end

#pass?(context) ⇒ Boolean

Returns:

  • (Boolean)


239
240
241
242
243
244
# File 'lib/declarative_policy/rule.rb', line 239

def pass?(context)
  cached = cached_pass?(context)
  return cached unless cached.nil?

  @rules.sort_by { |r| r.score(context) }.any? { |r| r.pass?(context) }
end

#reprObject



274
275
276
# File 'lib/declarative_policy/rule.rb', line 274

def repr
  "any?(#{@rules.map(&:repr).join(', ')})"
end

#score(context) ⇒ Object



268
269
270
271
272
# File 'lib/declarative_policy/rule.rb', line 268

def score(context)
  return 0 unless cached_pass?(context).nil?

  @rules.sum { |r| r.score(context) }
end

#simplifyObject



246
247
248
249
250
251
252
253
254
255
256
# File 'lib/declarative_policy/rule.rb', line 246

def simplify
  simplified_rules = @rules.flat_map do |rule|
    simplified = rule.simplify
    case simplified
    when Or then simplified.rules
    else [simplified]
    end
  end

  Or.new(simplified_rules)
end