Sha256: 27332cc8616e0d70db375c47eabc53af5b35c48d8229205d7080a7088c387a6f

Contents?: true

Size: 999 Bytes

Versions: 5

Compression:

Stored size: 999 Bytes

Contents

# frozen_string_literal: true

# A custom validator to check for presence in I18n-enabled fields. In order to
# use it do the following:
#
#   validates :my_i18n_field, translatable_presence: true
#
# This will automatically check for presence for each of the
# `available_locales` of the form object (or the `available_locales` of the
# form's organization) for the given field.
class TranslatablePresenceValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, _value)
    available_locales_for(record).each do |locale|
      translated_attr = "#{attribute}_#{locale}"
      record.errors.add(translated_attr, :blank) if record.send(translated_attr).blank?
    end
  end

  private

  def available_locales_for(record)
    return record.available_locales if record.respond_to?(:available_locales)

    if record.current_organization
      record.current_organization.available_locales
    else
      record.errors.add(:current_organization, :blank)
      []
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
decidim-core-0.7.4 app/forms/translatable_presence_validator.rb
decidim-core-0.7.3 app/forms/translatable_presence_validator.rb
decidim-core-0.7.2 app/forms/translatable_presence_validator.rb
decidim-core-0.7.1 app/forms/translatable_presence_validator.rb
decidim-core-0.7.0 app/forms/translatable_presence_validator.rb