Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Added presence constraint.

  • Loading branch information...
commit acb05bd02fc849f6a004e4b7ecd789b91b43d473 1 parent de73791
Josh Bassett authored
4 lib/rein.rb
View
@@ -8,10 +8,11 @@ module Constraint
require 'active_record'
require 'active_support/core_ext/hash'
-require 'rein/constraint/foreign_key'
require 'rein/constraint/primary_key'
+require 'rein/constraint/foreign_key'
require 'rein/constraint/inclusion'
require 'rein/constraint/numericality'
+require 'rein/constraint/presence'
require 'rein/view'
module ActiveRecord::ConnectionAdapters
@@ -32,6 +33,7 @@ class PostgreSQLAdapter < AbstractAdapter
include RC::ForeignKey
include RC::Inclusion
include RC::Numericality
+ include RC::Presence
include Rein::View
end
end
11 lib/rein/constraint/presence.rb
View
@@ -0,0 +1,11 @@
+module RC
+ module Presence
+ include ActiveRecord::ConnectionAdapters::Quoting
+
+ def add_presence_constraint(table, attribute)
+ name = "#{table}_#{attribute}"
+ conditions = "#{attribute} !~ '^\s*$'"
+ execute("ALTER TABLE #{table} ADD CONSTRAINT #{name} CHECK (#{conditions})")
+ end
+ end
+end
20 spec/rein/constraint/presence_spec.rb
View
@@ -0,0 +1,20 @@
+require 'spec_helper'
+
+describe RC::Presence, "#add_presence_constraint" do
+ let(:adapter) do
+ Class.new do
+ include RC::Presence
+ end.new
+ end
+
+ subject { adapter }
+
+ before do
+ stub(adapter).execute
+ end
+
+ context "given a table and attribute" do
+ before { adapter.add_presence_constraint(:books, :state) }
+ it { should have_received.execute("ALTER TABLE books ADD CONSTRAINT books_state CHECK (state !~ '^\s*$')") }
+ end
+end
Please sign in to comment.
Something went wrong with that request. Please try again.