Module: ActiveModel::BetterErrors::Emulation

Includes:
Enumerable
Included in:
Errors
Defined in:
lib/active_model/better_errors/emulation.rb

Overview

Emulation The ActiveModel Emulation Layer

Constant Summary collapse

MODEL_METHODS =
[
  :clear, :include?, :get, :set, :delete, :[], :[]=,
  :each, :size, :length, :values, :keys, :count, :empty?, :any?,
  :added?, :entries
]
MESSAGE_REPORTER_METHODS =
[
  :full_messages, :full_message, :generate_message
]

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/active_model/better_errors/emulation.rb', line 27

def self.included(base)
  base.class_eval do
    extend Forwardable
    def_delegators :error_collection, *MODEL_METHODS
    def_delegators :message_reporter, *MESSAGE_REPORTER_METHODS
    def_delegators :hash_reporter,    :to_hash
    def_delegators :array_reporter,   :to_a

    alias_method :blank?, :empty?
    alias_method :has_key?, :include?
  end
end

Instance Method Details

#add(attribute, message = nil, options = {}) ⇒ Object



55
56
57
58
59
60
61
62
63
# File 'lib/active_model/better_errors/emulation.rb', line 55

def add(attribute, message = nil, options = {})
  if options[:strict]
    error   = ErrorMessage.build(attribute, message, options)
    message = ::ActiveModel::BetterErrors.format_message(@base, error)
    full_message = full_message(attribute, message)
    fail ActiveModel::StrictValidationFailed, full_message
  end
  error_collection.add attribute, message, options
end

#add_on_blank(attributes, options = {}) ⇒ Object



48
49
50
51
52
53
# File 'lib/active_model/better_errors/emulation.rb', line 48

def add_on_blank(attributes, options = {})
  [attributes].flatten.each do |attribute|
    value = @base.send(:read_attribute_for_validation, attribute)
    add(attribute, :blank, options) if value.blank?
  end
end

#add_on_empty(attributes, options = {}) ⇒ Object



40
41
42
43
44
45
46
# File 'lib/active_model/better_errors/emulation.rb', line 40

def add_on_empty(attributes, options = {})
  [attributes].flatten.each do |attribute|
    value = @base.send(:read_attribute_for_validation, attribute)
    is_empty = value.respond_to?(:empty?) ? value.empty? : false
    add(attribute, :empty, options) if value.nil? || is_empty
  end
end

#as_json(options = nil) ⇒ Object



69
70
71
# File 'lib/active_model/better_errors/emulation.rb', line 69

def as_json(options = nil)
  to_hash
end

#to_xml(options = {}) ⇒ Object



65
66
67
# File 'lib/active_model/better_errors/emulation.rb', line 65

def to_xml(options = {})
  to_a.to_xml options.reverse_merge(root: 'errors', skip_types: true)
end