Sha256: 5b4f2184134dd016a96378696327cc7e0117793f5638f754e04b2303f92b8030

Contents?: true

Size: 1.35 KB

Versions: 2

Compression:

Stored size: 1.35 KB

Contents

require 'rein/util'

module Rein
  module Constraint
    # This module contains methods for defining presence constraints.
    module Presence
      include ActiveRecord::ConnectionAdapters::Quoting

      def add_presence_constraint(*args)
        reversible do |dir|
          dir.up { _add_presence_constraint(*args) }
          dir.down { _remove_presence_constraint(*args) }
        end
      end

      def remove_presence_constraint(*args)
        reversible do |dir|
          dir.up { _remove_presence_constraint(*args) }
          dir.down { _add_presence_constraint(*args) }
        end
      end

      private

      def _add_presence_constraint(table, attribute, options = {})
        name = Util.constraint_name(table, attribute, 'presence', options)
        table = Util.wrap_identifier(table)
        attribute = Util.wrap_identifier(attribute)
        conditions = Util.conditions_with_if(
          "(#{attribute} IS NOT NULL) AND (#{attribute} !~ '^\\s*$')",
          options
        )
        execute("ALTER TABLE #{table} ADD CONSTRAINT #{name} CHECK (#{conditions})")
      end

      def _remove_presence_constraint(table, attribute, options = {})
        name = Util.constraint_name(table, attribute, 'presence', options)
        table = Util.wrap_identifier(table)
        execute("ALTER TABLE #{table} DROP CONSTRAINT #{name}")
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
rein-5.0.0 lib/rein/constraint/presence.rb
rein-4.0.0 lib/rein/constraint/presence.rb