Module: Rein::Constraint::Numericality

Included in:
ActiveRecord::ConnectionAdapters::PostgreSQLAdapter
Defined in:
lib/rein/constraint/numericality.rb

Overview

This module contains methods for defining numericality constraints.

Constant Summary collapse

OPERATORS =
{
  greater_than: :>,
  greater_than_or_equal_to: :>=,
  equal_to: :"=",
  not_equal_to: :"!=",
  less_than: :<,
  less_than_or_equal_to: :<=
}.freeze

Instance Method Summary collapse

Instance Method Details

#add_numericality_constraint(table, attribute, options = {}) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/rein/constraint/numericality.rb', line 14

def add_numericality_constraint(table, attribute, options = {})
  name = "#{table}_#{attribute}"

  conditions = OPERATORS.slice(*options.keys).map do |key, operator|
    value = options[key]
    [attribute, operator, value].join(" ")
  end.join(" AND ")

  if options[:if].present?
    conditions = "NOT (#{options[:if]}) OR (#{conditions})"
  end

  execute("ALTER TABLE #{table} ADD CONSTRAINT #{name} CHECK (#{conditions})")
end

#remove_numericality_constraint(table, attribute) ⇒ Object



29
30
31
32
# File 'lib/rein/constraint/numericality.rb', line 29

def remove_numericality_constraint(table, attribute)
  name = "#{table}_#{attribute}"
  execute("ALTER TABLE #{table} DROP CONSTRAINT #{name}")
end