Class: DeclarativePolicy::Rule::And

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

Overview

Logical ‘and`, containing a list of rules. Only passes if all of them do.

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Base

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

Constructor Details

#initialize(rules) ⇒ And

Returns a new instance of And.



184
185
186
# File 'lib/declarative_policy/rule.rb', line 184

def initialize(rules)
  @rules = rules
end

Instance Attribute Details

#rulesObject (readonly)

Returns the value of attribute rules.



182
183
184
# File 'lib/declarative_policy/rule.rb', line 182

def rules
  @rules
end

Instance Method Details

#cached_pass?(context) ⇒ Boolean

Returns:

  • (Boolean)


216
217
218
219
220
221
222
223
224
# File 'lib/declarative_policy/rule.rb', line 216

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

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

  true
end

#pass?(context) ⇒ Boolean

Returns:

  • (Boolean)


207
208
209
210
211
212
213
214
# File 'lib/declarative_policy/rule.rb', line 207

def pass?(context)
  # try to find a cached answer before
  # checking in order
  cached = cached_pass?(context)
  return cached unless cached.nil?

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

#reprObject



226
227
228
# File 'lib/declarative_policy/rule.rb', line 226

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

#score(context) ⇒ Object



200
201
202
203
204
205
# File 'lib/declarative_policy/rule.rb', line 200

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

  # note that cached rules will have score 0 anyways.
  @rules.sum { |r| r.score(context) }
end

#simplifyObject



188
189
190
191
192
193
194
195
196
197
198
# File 'lib/declarative_policy/rule.rb', line 188

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

  And.new(simplified_rules)
end