Sha256: b657662f5c7c2bdd0308348cef0b45aba951a95b24738699be11a431e2e50f41

Contents?: true

Size: 1.51 KB

Versions: 3

Compression:

Stored size: 1.51 KB

Contents

require "rein/util"

module Rein
  module Constraint
    # This module contains methods for defining numericality constraints.
    module Numericality
      OPERATORS = {
        greater_than: :>,
        greater_than_or_equal_to: :>=,
        equal_to: :"=",
        not_equal_to: :"!=",
        less_than: :<,
        less_than_or_equal_to: :<=
      }.freeze

      def add_numericality_constraint(*args)
        reversible do |dir|
          dir.up { _add_numericality_constraint(*args) }
          dir.down { _remove_numericality_constraint(*args) }
        end
      end

      def remove_numericality_constraint(*args)
        reversible do |dir|
          dir.up { _remove_numericality_constraint(*args) }
          dir.down { _add_numericality_constraint(*args) }
        end
      end

      private

      def _add_numericality_constraint(table, attribute, options = {})
        name = Util.constraint_name(table, attribute, "numericality", options)
        conditions = OPERATORS.slice(*options.keys).map do |key, operator|
          value = options[key]
          [attribute, operator, value].join(" ")
        end.join(" AND ")
        conditions = Util.conditions_with_if(conditions, options)
        execute("ALTER TABLE #{table} ADD CONSTRAINT #{name} CHECK (#{conditions})")
      end

      def _remove_numericality_constraint(table, attribute, options = {})
        name = Util.constraint_name(table, attribute, "numericality", options)
        execute("ALTER TABLE #{table} DROP CONSTRAINT #{name}")
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
rein-3.2.0 lib/rein/constraint/numericality.rb
rein-3.1.0 lib/rein/constraint/numericality.rb
rein-3.0.0 lib/rein/constraint/numericality.rb