Class: Plumb::Policies
- Inherits:
-
Object
- Object
- Plumb::Policies
- Defined in:
- lib/plumb/policies.rb
Overview
A policy registry for Plumb It holds and gets registered policies. Policies are callable objects that act as factories for type compositions.
Constant Summary collapse
- UnknownPolicyError =
Class.new(StandardError)
- MethodAlreadyDefinedError =
Class.new(StandardError)
Instance Method Summary collapse
-
#get(types, name) ⇒ #call
Get a policy for a given type.
-
#initialize ⇒ Policies
constructor
A new instance of Policies.
-
#register(for_type, name, policy) ⇒ Object
Register a policy for all or specific outpyt types.
Constructor Details
#initialize ⇒ Policies
Returns a new instance of Policies.
13 14 15 |
# File 'lib/plumb/policies.rb', line 13 def initialize @policies = {} end |
Instance Method Details
#get(types, name) ⇒ #call
Get a policy for a given type.
44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/plumb/policies.rb', line 44 def get(types, name) if (pol = resolve_shared_policy(types, name)) pol elsif (pol = @policies.dig(name, Object)) raise UnknownPolicyError, "Unknown policy #{name} for #{types.inspect}" unless pol pol else raise UnknownPolicyError, "Unknown or incompatible policy #{name} for #{types.inspect}" end end |
#register(for_type, name, policy) ⇒ Object
Register a policy for all or specific outpyt types. Example for a policy that works for all types:
#register(Object, :my_policy, ->(node, arg) { ... })
Example for a policy that works for a specific type:
#register(String, :my_policy, ->(node, arg) { ... })
Example for a policy that works for a specific interface:
#register(:size, :my_policy, ->(node, arg) { ... })
The policy callable takes the step it is applied to, a policy argument (if any) and a policy block (if any). Example for a policy #default(default_value = Undefined) { ‘some-default-value’ }
policy = proc do |type, default_value = Undefined, &block|
type | (Plumb::Types::Undefined >> Plumb::Types::Static[default_value])
end
34 35 36 37 |
# File 'lib/plumb/policies.rb', line 34 def register(for_type, name, policy) @policies[name] ||= {} @policies[name][for_type] = policy end |