module BloodContracts::Core::DefineableError::Concern

Concern with the helper to define custom Tram::Policy::Errors

Public Instance Methods

define_error(message, tags: {}, sub_scope: nil) click to toggle source

Method that turns message into Tram::Policy::Errors object

@param message [String, Symbol] (or translations key) for your

custom error

@option tags [Hash] additional context for translations @option sub_scope [Symbol] is a customizable path to your

translation

@return [Tram::Policy::Error]

# File lib/blood_contracts/core/defineable_error.rb, line 21
def define_error(message, tags: {}, sub_scope: nil)
  errors = Tram::Policy::Errors.new(scope: @policy_scope)
  sub_scope = underscore(sub_scope || name)
  message = [sub_scope, message].join(".").to_sym if message.is_a?(Symbol)
  errors.add message, **tags
  errors
end
inherited(other) click to toggle source

@private

Calls superclass method
# File lib/blood_contracts/core/defineable_error.rb, line 7
def inherited(other)
  super
  other.instance_variable_set(:@policy_scope, @policy_scope)
end

Private Instance Methods

underscore(string) click to toggle source

@private

# File lib/blood_contracts/core/defineable_error.rb, line 30
        def underscore(string)
  return string.underscore if string.respond_to?(:underscore)

  string.gsub(/([A-Z]+)([A-Z])/, '\1_\2')
        .gsub(/([a-z])([A-Z])/, '\1_\2')
        .gsub("__", "/")
        .gsub("::", "/")
        .gsub(/\s+/, "") # spaces are bad form
        .gsub(/[?%*:|"<>.]+/, "") # reserved characters
        .downcase
end