Sha256: 09fd36624cfa54e7711a08d0c526538c67aa4ea684eb23f16a3ee8219b3b0755

Contents?: true

Size: 1.24 KB

Versions: 3

Compression:

Stored size: 1.24 KB

Contents

require "rein/util"

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

      def add_inclusion_constraint(*args)
        reversible do |dir|
          dir.up { _add_inclusion_constraint(*args) }
          dir.down { _remove_inclusion_constraint(*args) }
        end
      end

      def remove_inclusion_constraint(*args)
        reversible do |dir|
          dir.up { _remove_inclusion_constraint(*args) }
          dir.down { _add_inclusion_constraint(*args) }
        end
      end

      private

      def _add_inclusion_constraint(table, attribute, options = {})
        name = Util.constraint_name(table, attribute, "inclusion", options)
        values = options[:in].map { |value| quote(value) }.join(", ")
        conditions = Util.conditions_with_if("#{attribute} IN (#{values})", options)
        execute("ALTER TABLE #{table} ADD CONSTRAINT #{name} CHECK (#{conditions})")
      end

      def _remove_inclusion_constraint(table, attribute, options = {})
        name = Util.constraint_name(table, attribute, "inclusion", 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/inclusion.rb
rein-3.1.0 lib/rein/constraint/inclusion.rb
rein-3.0.0 lib/rein/constraint/inclusion.rb