Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Failing calls to has_bit_field should raise an exception unless explicitly configured otherwise. #18

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
17 changes: 16 additions & 1 deletion 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
Expand Down
13 changes: 12 additions & 1 deletion test/has-bit-field_test.rb
Expand Up @@ -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
Expand Down Expand Up @@ -206,12 +209,20 @@ 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
end
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