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.


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

def initialize(rules)
  @rules = rules
end

Instance Attribute Details

#rulesObject (readonly)

Returns the value of attribute rules


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

def rules
  @rules
end

Instance Method Details

#cached_pass?(context) ⇒ Boolean

Returns:

  • (Boolean)

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

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)

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

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

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

#reprObject


224
225
226
# File 'lib/declarative_policy/rule.rb', line 224

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

#score(context) ⇒ Object


198
199
200
201
202
203
# File 'lib/declarative_policy/rule.rb', line 198

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

  # note that cached rules will have score 0 anyways.
  @rules.map { |r| r.score(context) }.inject(0, :+)
end

#simplifyObject


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

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