Sha256: e4a655894c86b946c9be086917e47f4aca50cb8f402f8e697270300fc2066044

Contents?: true

Size: 962 Bytes

Versions: 25

Compression:

Stored size: 962 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 the default locale of the form
# object (or the `default_locale` of the form's organization) for the given field.
class TranslatablePresenceValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, _value)
    translated_attr = "#{attribute}_#{default_locale_for(record)}".gsub("-", "__")
    record.errors.add(translated_attr, :blank) if record.send(translated_attr).blank?
  end

  private

  def default_locale_for(record)
    return record.default_locale if record.respond_to?(:default_locale)

    if record.current_organization
      record.current_organization.default_locale
    else
      record.errors.add(:current_organization, :blank)
      Decidim.default_locale
    end
  end
end

Version data entries

25 entries across 25 versions & 1 rubygems

Version Path
decidim-core-0.29.1 app/validators/translatable_presence_validator.rb
decidim-core-0.28.4 app/validators/translatable_presence_validator.rb
decidim-core-0.27.9 app/forms/translatable_presence_validator.rb
decidim-core-0.29.0 app/validators/translatable_presence_validator.rb
decidim-core-0.28.3 app/validators/translatable_presence_validator.rb
decidim-core-0.27.8 app/forms/translatable_presence_validator.rb
decidim-core-0.29.0.rc4 app/validators/translatable_presence_validator.rb
decidim-core-0.29.0.rc3 app/validators/translatable_presence_validator.rb
decidim-core-0.29.0.rc2 app/validators/translatable_presence_validator.rb
decidim-core-0.29.0.rc1 app/validators/translatable_presence_validator.rb
decidim-core-0.28.2 app/validators/translatable_presence_validator.rb
decidim-core-0.27.7 app/forms/translatable_presence_validator.rb
decidim-core-0.28.1 app/validators/translatable_presence_validator.rb
decidim-core-0.27.6 app/forms/translatable_presence_validator.rb
decidim-core-0.28.0 app/validators/translatable_presence_validator.rb
decidim-core-0.27.5 app/forms/translatable_presence_validator.rb
decidim-core-0.28.0.rc5 app/validators/translatable_presence_validator.rb
decidim-core-0.28.0.rc4 app/validators/translatable_presence_validator.rb
decidim-core-0.27.4 app/forms/translatable_presence_validator.rb
decidim-core-0.27.3 app/forms/translatable_presence_validator.rb