-
Notifications
You must be signed in to change notification settings - Fork 36
/
tag_validations.rb
58 lines (47 loc) · 1.29 KB
/
tag_validations.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# 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 << ActiveRecord::ConnectionNotEstablished
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