Module: Errorio
- Defined in:
- lib/errorio.rb,
lib/errorio/error.rb,
lib/errorio/errors.rb,
lib/errorio/details.rb,
lib/errorio/version.rb
Overview
Errorio
Extend your models and classes with errors, warnings and other notices
Examples:
Extend ordinary AR model with special collection of warnings
and notices
class Task < ApplicationRecord
include Errorio
errorionize :errors, :warnings, :notices # :errors is initialized by ActiveRecord, so it is redundant in this case
validates :name, presence: { code: :E0230 }
validate :special_characters_validation
private
def special_characters_validation
return if name =~ /^[a-z0-9]*$/i
exceptions = name.gsub(/[^a-z0-9]/i).map{ |a| "'#{a}'" }.join(','),
warnings.add(:name, :special_characters, code: :E0231,
chars: exceptions,
message: 'Special characters are not recommended for name')
end
end
result = Task.create result.errors.to_e
>
[
{
:code=>:E0230,
:key=>:name,
:type=>:blank,
:message=>"Task Name can't be blank"
}
]
result = Task.create ‘Do * now!’ result.errors.to_e
>
-
result.warnings.to_e
>
[
{ :code=>:E0231, :key=>:name, :type=>:special_characters, :message=>"Special characters ('*', '!') are not recommended for name" }
]
Message should be described in en.yml file
errorio:
messages: E0231: "Special characters (%{chars}) are not recommended for name"
Implement errors and warnings to service class
class Calculate
include Errorio errorionize :errors, :warnings def initialize(a, b) @a = a @b = b end def sum return unless valid? a + b end def valid? return true if @a.is_a?(Numeric) && @b.is_a?(Numeric) errors.add :base, :not_a_numeric, Errorio.by_code(:E1000A) end
end
calc = Calculate.new(3, ‘1’) if (result = calc.sum)
puts result
else
puts calc.errors.to_e
end
> # [
{ :code=>:E1000A, :key=>:base, :type=>:not_a_numeric, :message=>"Special characters are not recommended for name" }
]
Defined Under Namespace
Modules: ClassMethods, ErrorObjectsMethods, InstanceMethods Classes: Details, Error, Errors
Constant Summary collapse
- VERSION =
'0.1.9'.freeze
Class Method Summary collapse
-
.by_code(*args) ⇒ Object
Error details with code.
- .included(base) ⇒ Object
-
.message(code, args = {}) ⇒ String
Interpolate error message from i18n.
Class Method Details
.by_code(*args) ⇒ Object
Error details with code
errors.add :base, :invalid, Errorio.by_code(:E0001, user_id: 129)
109 110 111 |
# File 'lib/errorio.rb', line 109 def by_code(*args) Details.by_code(*args) end |
.included(base) ⇒ Object
125 126 127 128 129 130 131 132 133 |
# File 'lib/errorio.rb', line 125 def self.included(base) base.extend ClassMethods base.send :prepend, InstanceMethods # Patch for ActiveRecord classes # AR doesn't call `initialize` method for objects that created on data that was fetched from database, # so you cannot override it. You must use `after_initialize` callback to do that. base.after_initialize :errorio_initializer if base.respond_to?(:after_initialize) end |