Class: SpicyValidation::Validation

Inherits:
Object
  • Object
show all
Defined in:
lib/spicy_validation/validation.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(method_name:, column_name:, options:) ⇒ Validation

Returns a new instance of Validation.



9
10
11
12
13
# File 'lib/spicy_validation/validation.rb', line 9

def initialize(method_name:, column_name:, options:)
  @method_name = method_name
  @column_name = column_name
  @options = options
end

Instance Attribute Details

#column_nameObject (readonly)

Returns the value of attribute column_name.



7
8
9
# File 'lib/spicy_validation/validation.rb', line 7

def column_name
  @column_name
end

#method_nameObject (readonly)

Returns the value of attribute method_name.



7
8
9
# File 'lib/spicy_validation/validation.rb', line 7

def method_name
  @method_name
end

#optionsObject (readonly)

Returns the value of attribute options.



7
8
9
# File 'lib/spicy_validation/validation.rb', line 7

def options
  @options
end

Class Method Details

.normal_validations(table_name:) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
# File 'lib/spicy_validation/validation.rb', line 15

def self.normal_validations(table_name:)
  columns = Schema.columns(table_name: table_name)
  columns = columns.reject { |x| x.name.in? %w[id created_at updated_at] }
  columns.map do |column|
    options = {}
    options[:presence] = true unless column.null
    options[:numericality] = true if column.type == :integer
    options[:allow_nil] = true if column.null && (column.type == :integer)
    Validation.new(method_name: "validates", column_name: column.name.to_sym, options: options) if options.present?
  end.compact
end

.unique_validations(table_name:) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/spicy_validation/validation.rb', line 27

def self.unique_validations(table_name:)
  Schema.indexes(table_name: table_name).map do |index|
    column_name = index.columns[0]
    scope = index.columns[1..-1].map(&:to_sym)
    options = if scope.size > 1
                { scope: scope }
              elsif scope.size == 1
                { scope: scope[0] }
              end
    Validation.new(method_name: "validates_uniqueness_of", column_name: column_name.to_sym, options: options)
  end
end

Instance Method Details

#to_sObject



40
41
42
43
44
45
46
# File 'lib/spicy_validation/validation.rb', line 40

def to_s
  if options.blank?
    "#{method_name} #{column_name.inspect}"
  else
    "#{method_name} #{column_name.inspect}, #{options.format_hash}"
  end
end