Sha256: a9dd32e15a9ed8f670db686a5eda5a8579d3387d41cdb28f2b874e282e6b9ffc

Contents?: true

Size: 1.12 KB

Versions: 22

Compression:

Stored size: 1.12 KB

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)
    # Transform Rails foo[bar] convention to foo.bar
    field = field.gsub('[', '.').gsub(']', '')

    validation_errors[field] || []
  end

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

    field_errors(field).each { |e| yield(e) }
  end
end

Version data entries

22 entries across 22 versions & 1 rubygems

Version Path
mini_defender-0.6.8 lib/mini_defender/validation_helpers.rb
mini_defender-0.6.7 lib/mini_defender/validation_helpers.rb
mini_defender-0.6.5 lib/mini_defender/validation_helpers.rb
mini_defender-0.6.4 lib/mini_defender/validation_helpers.rb
mini_defender-0.6.3 lib/mini_defender/validation_helpers.rb
mini_defender-0.6.2 lib/mini_defender/validation_helpers.rb
mini_defender-0.6.1 lib/mini_defender/validation_helpers.rb
mini_defender-0.6.0 lib/mini_defender/validation_helpers.rb
mini_defender-0.5.8 lib/mini_defender/validation_helpers.rb
mini_defender-0.5.7 lib/mini_defender/validation_helpers.rb
mini_defender-0.5.6 lib/mini_defender/validation_helpers.rb
mini_defender-0.5.5 lib/mini_defender/validation_helpers.rb
mini_defender-0.5.4 lib/mini_defender/validation_helpers.rb
mini_defender-0.5.3 lib/mini_defender/validation_helpers.rb
mini_defender-0.5.2 lib/mini_defender/validation_helpers.rb
mini_defender-0.5.1 lib/mini_defender/validation_helpers.rb
mini_defender-0.5.0 lib/mini_defender/validation_helpers.rb
mini_defender-0.4.1 lib/mini_defender/validation_helpers.rb
mini_defender-0.4.0 lib/mini_defender/validation_helpers.rb
mini_defender-0.3.14 lib/mini_defender/validation_helpers.rb