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/validation_error.rb

Overview

Base class for policy objects with composable validation errors

Defined Under Namespace

Classes: Error, Errors, Generator, ValidationError

Constant Summary collapse

Inflector =
::Inflecto

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

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

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

Parameters:

  • *args (Object)

Returns:


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

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

.validate(*names) ⇒ self

Registers a validator

Parameters:

  • names (#to_sym, Array<#to_sym>)

Returns:

  • (self)

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

def validate(*names)
  @validators = validators | names.flatten.map(&:to_sym)
  self
end

Instance Method Details

#errorsTram::Policy::Errors

Collection of validation errors


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

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"]>

Returns:

  • (String)

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

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

#invalid?(&filter) ⇒ Boolean

Checks whether the policy is invalid

Parameters:

  • filter (Proc, nil)

    Block describing **the only errors to count**

Returns:

  • (Boolean)

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

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

#t(message, **options) ⇒ String

Translates a message in the scope of current policy

Parameters:

  • message (#to_s)
  • options (Hash<Symbol, Object>)

Returns:

  • (String)

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

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

Parameters:

  • filter (Proc, nil)

    Block describing **errors to be skipped**

Returns:

  • (Boolean)

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

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

#validate!(&filter) ⇒ nil

Raises exception if the policy is not valid

Parameters:

  • filter (Proc, nil)

    Block describing **errors to be skipped**

Returns:

  • (nil)

    if the policy is valid

Raises:


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

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