From 4af1619749d0ec2e64f437e96ff9037702649010 Mon Sep 17 00:00:00 2001 From: JD Huntington Date: Mon, 10 Feb 2014 21:00:05 -0800 Subject: [PATCH] Failing calls to has_bit_field should raise an exception unless explicitly configured otherwise. --- lib/has-bit-field.rb | 17 ++++++++++++++++- test/has-bit-field_test.rb | 13 ++++++++++++- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/lib/has-bit-field.rb b/lib/has-bit-field.rb index 3a49785..6b92ee7 100644 --- a/lib/has-bit-field.rb +++ b/lib/has-bit-field.rb @@ -1,17 +1,32 @@ module HasBitField + + def self.silently_fail=(val) + @silently_fail = val + end + + def self.silently_fail? + @silently_fail || false + end + # The first arguement +bit_field_attribute+ should be a symbol, # the name of attribute that will hold the actual bit field # all following arguments should also be symbols, # which will be the name of each flag in the bit field def has_bit_field(bit_field_attribute, *args) unless table_exists? + msg = "[has_bit_field] table undefined #{table_name}" + raise ArgumentError.new(msg) unless HasBitField.silently_fail? Rails.logger.error("[has_bit_field] table undefined #{table_name}") if defined?(Rails) && Rails.respond_to?(:logger) return end + if columns_hash[bit_field_attribute.to_s].blank? - Rails.logger.error("[has_bit_field] column undefined #{bit_field_attribute}") if defined?(Rails) && Rails.respond_to?(:logger) + msg = "[has_bit_field] column undefined #{bit_field_attribute} (in #{table_name})" + raise ArgumentError.new(msg) unless HasBitField.silently_fail? + Rails.logger.error(msg) if defined?(Rails) && Rails.respond_to?(:logger) return end + args.each_with_index do |field,i| class_eval %{ class << self diff --git a/test/has-bit-field_test.rb b/test/has-bit-field_test.rb index 51bde6e..a5c0c94 100644 --- a/test/has-bit-field_test.rb +++ b/test/has-bit-field_test.rb @@ -34,6 +34,9 @@ class Skill < ActiveRecord::Base end class HasBitFieldTest < Test::Unit::TestCase + def setup + HasBitField.silently_fail = false + end def test_bit_field p = Person.new @@ -206,7 +209,8 @@ def test_ar_validations_with_default assert s.save end - def test_environment_will_not_die_on_undefined_fields + def test_environment_will_not_die_on_undefined_fields_with_silently_fail_set + HasBitField.silently_fail = true assert_nothing_raised do Person.class_eval do has_bit_field :not_a_happy_field, :if_only_it_existed, :but_its_not_in_the_db, :we_had_hoped_for_it_but_its_not_there, :silence @@ -214,4 +218,11 @@ def test_environment_will_not_die_on_undefined_fields end end + def test_environment_will_die_on_undefined_fields_with_silently_fail_unset + assert_raise(ArgumentError) do + Person.class_eval do + has_bit_field :not_a_happy_field, :if_only_it_existed, :but_its_not_in_the_db, :we_had_hoped_for_it_but_its_not_there, :silence + end + end + end end