Class: Tram::Policy

Inherits:
Object
  • Object
show all
Extended by:
Dry::Initializer
Defined in:
lib/tram/policy.rb,
lib/tram/policy/error.rb,
lib/tram/policy/errors.rb,
lib/tram/policy/generator.rb,
lib/tram/policy/inflector.rb,
lib/tram/policy/validator.rb,
lib/tram/policy/validation_error.rb

Overview

Base class for policy objects with composable validation errors

Defined Under Namespace

Modules: Inflector Classes: Error, Errors, Generator, ValidationError, Validator

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.[](*args) ⇒ Tram::Policy

Policy constructor/validator (alias for [.new])



31
32
33
# File 'lib/tram/policy.rb', line 31

def [](*args)
  new(*args)
end

.validate(name, **opts) ⇒ self

Registers a validator



21
22
23
24
# File 'lib/tram/policy.rb', line 21

def validate(name, **opts)
  validators[name.to_sym] = opts
  self
end

Instance Method Details

#errorsTram::Policy::Errors

Collection of validation errors



62
63
64
# File 'lib/tram/policy.rb', line 62

def errors
  @errors ||= Errors.new(self)
end

#inspectString

Human-readable representation of the policy

Examples:

Displays policy name and its attributes

UserPolicy[name: "Andy"].inspect
# => #<UserPolicy["name" => "Andy"]>


102
103
104
# File 'lib/tram/policy.rb', line 102

def inspect
  "#<#{self.class.name}[#{@__options__}]>"
end

#invalid?(&filter) ⇒ Boolean

Checks whether the policy is invalid



80
81
82
# File 'lib/tram/policy.rb', line 80

def invalid?(&filter)
  filter ? errors.any?(&filter) : errors.any?
end

#t(message, **options) ⇒ String

Translates a message in the scope of current policy



53
54
55
56
# File 'lib/tram/policy.rb', line 53

def t(message, **options)
  return message.to_s unless message.is_a? Symbol
  I18n.t message, options.merge(scope: @__scope__)
end

#valid?(&filter) ⇒ Boolean

Checks whether the policy is valid



71
72
73
# File 'lib/tram/policy.rb', line 71

def valid?(&filter)
  filter ? errors.reject(&filter).empty? : errors.empty?
end

#validate!(&filter) ⇒ nil

Raises exception if the policy is not valid

Raises:



90
91
92
# File 'lib/tram/policy.rb', line 90

def validate!(&filter)
  raise ValidationError.new(self, filter) unless valid?(&filter)
end