Sha256: 9111e7a09e015dc2f8b5ec8e96c01a1926e685a3653e321e15222c9b9303a932

Contents?: true

Size: 1.23 KB

Versions: 3

Compression:

Stored size: 1.23 KB

Contents

# frozen_string_literal: true

require "active_model/errors"
require "active_record/errors"

class Gutentag::TagValidations
  DEFAULTS = {
    :presence   => true,
    :uniqueness => {:case_sensitive => false}
  }.freeze
  DATABASE_ERROR_CLASSES = lambda {
    classes = []
    if ActiveRecord::VERSION::STRING.to_f > 4.0
      classes << ActiveRecord::NoDatabaseError
    end
    classes << Mysql2::Error     if defined?(::Mysql2)
    classes << PG::ConnectionBad if defined?(::PG)
    classes
  }.call.freeze

  def self.call(klass)
    new(klass).call
  end

  def initialize(klass)
    @klass = klass
  end

  def call
    klass.validates :name, validation_options.dup
  end

  private

  attr_reader :klass

  def add_length_validation?
    klass.table_exists? && limit.present?
  rescue *DATABASE_ERROR_CLASSES => _error
    warn <<-MESSAGE
  The database is not currently available, and so Gutentag was not able to set
  up tag validations completely (in particular: adding a length limit to match
  database constraints).
    MESSAGE
    false
  end

  def limit
    @limit ||= klass.columns_hash["name"].limit
  end

  def validation_options
    return DEFAULTS unless add_length_validation?

    DEFAULTS.merge :length => {:maximum => limit}
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
gutentag-2.5.3 lib/gutentag/tag_validations.rb
gutentag-2.5.2 lib/gutentag/tag_validations.rb
gutentag-2.5.1 lib/gutentag/tag_validations.rb