Skip to content

Instantly share code, notes, and snippets.

@greatseth
Created March 4, 2009 20:56
Show Gist options
  • Select an option

  • Save greatseth/73999 to your computer and use it in GitHub Desktop.

Select an option

Save greatseth/73999 to your computer and use it in GitHub Desktop.
# Include in ActiveRecord::Base to have your models automatically convert
# empty strings and the like to nil before save.
module StringNullifier
def self.included(model)
model.class_eval do
extend StringAttributesAccessor
before_validation :nullify_strings
end
end
module StringAttributesAccessor
def string_attributes
columns.select { |c| c.type == :string }.map { |c| c.name.to_sym }
end
end
private
def nullify_strings
self.class.string_attributes.each do |attribute|
if (v = send attribute) and v.is_a?(String) and v.strip.empty?
send "#{attribute}=", nil
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment