Sha256: f8c96df0509ca8722bf1c5c511c4a715148108e85a1e6d645f7c11fa4b600102

Contents?: true

Size: 983 Bytes

Versions: 1

Compression:

Stored size: 983 Bytes

Contents

# frozen_string_literal: true

require 'active_support/core_ext/hash'

module MiniDefender::ValidationHelpers
  extend ActiveSupport::Concern

  def validation_errors
    @validation_errors ||= flash[:validation_errors] || {}
  end

  def has_validation_errors?
    validation_errors.length > 0
  end

  def old_values
    @old_values ||= flash[:old_values] || {}
  end

  def old_value(field, default = nil)
    # Transform Rails foo[bar] convention to foo.bar
    field = field.gsub('[', '.').gsub(']', '')
    field = field.split('.')

    result = old_values.deep_stringify_keys

    while (key = field.shift)
      key = key.to_i if Array === result

      if Hash === result[key] || Array === result[key] || field.empty?
        result = result[key]
      end
    end

    result || default
  end

  def field_errors(field)
    raise ArgumentError, 'Expected a block.' unless block_given?

    errors = validation_errors[field] || []
    errors.each { |e| yield(e) }
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
mini_defender-0.3.11 lib/mini_defender/validation_helpers.rb