Class: DeclarativePolicy::ManifestCondition

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

Overview

In contrast to a Condition, a ManifestCondition contains a Condition and a context object, and is capable of calculating a result itself. This is the return value of Base#condition.

Instance Method Summary collapse

Constructor Details

#initialize(condition, context) ⇒ ManifestCondition

Returns a new instance of ManifestCondition.


35
36
37
38
# File 'lib/declarative_policy/condition.rb', line 35

def initialize(condition, context)
  @condition = condition
  @context = context
end

Instance Method Details

#cached?Boolean

Whether we've already computed this condition.

Returns:

  • (Boolean)

48
49
50
# File 'lib/declarative_policy/condition.rb', line 48

def cached?
  @context.cached?(cache_key)
end

#pass?Boolean

The main entry point - does this condition pass? We reach into the context's cache here so that we can share in the global cache (often RequestStore or similar).

Returns:

  • (Boolean)

43
44
45
# File 'lib/declarative_policy/condition.rb', line 43

def pass?
  @context.cache(cache_key) { @condition.compute(@context) }
end

#scoreObject

This is used to score Rule::Condition. See Rule::Condition#score and Runner#steps_by_score for how scores are used.

The number here is intended to represent, abstractly, how expensive it would be to calculate this condition.

See #cache_key for info about @condition.scope.


59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/declarative_policy/condition.rb', line 59

def score
  # If we've been cached, no computation is necessary.
  return 0 if cached?

  # Use the override from condition(score: ...) if present
  return @condition.manual_score if @condition.manual_score

  # Global scope rules are cheap due to max cache sharing
  return 2 if  @condition.scope == :global

  # "Normal" rules can't share caches with any other policies
  return 16 if @condition.scope == :normal

  # otherwise, we're :user or :subject scope, so it's 4 if
  # the caller has declared a preference
  return 4 if @condition.scope == DeclarativePolicy.preferred_scope

  # and 8 for all other :user or :subject scope conditions.
  8
end