Sha256: 1dc2f33d12a5d5942df8011f12b3aad9b440417a7b494c4c7a2dffb18ffbea15

Contents?: true

Size: 1.37 KB

Versions: 2

Compression:

Stored size: 1.37 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)
        table = Util.wrap_identifier(table)
        values = options[:in].map { |value| quote(value) }.join(', ')
        attribute = Util.wrap_identifier(attribute)
        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)
        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/inclusion.rb
rein-4.0.0 lib/rein/constraint/inclusion.rb