Created
March 4, 2009 20:56
-
-
Save greatseth/73999 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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