Sha256: 6428779bbf258a992472a3e04e866d6a245ae6af9a70eb810e8ae88e65510994

Contents?: true

Size: 1.38 KB

Versions: 2

Compression:

Stored size: 1.38 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 do _add_inclusion_constraint(*args) end
          dir.down { _remove_inclusion_constraint(*args) }
        end
      end

      def remove_inclusion_constraint(*args)
        reversible do |dir|
          dir.up do _remove_inclusion_constraint(*args) end
          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-3.5.0 lib/rein/constraint/inclusion.rb
rein-3.4.0 lib/rein/constraint/inclusion.rb