Created
January 26, 2010 22:40
-
-
Save snusnu/287322 to your computer and use it in GitHub Desktop.
This file contains 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
module ParameterSanitization | |
# Convert blank strings to nil if type is Integer and nils are allowed | |
# | |
# @example | |
# | |
# class User | |
# | |
# include DataMapper::Resource | |
# | |
# property :id, Serial | |
# property :some_fk_id, Integer | |
# | |
# extend ParameterSanitization | |
# | |
# treat_blank_as_nil :sales_group_id | |
# | |
# end | |
# | |
def treat_blank_as_nil(*args) | |
raise ArgumentError unless args.all? { |arg| properties[arg.to_sym] } | |
args.map { |arg| arg.to_sym }.each do |p| | |
if properties[p].type == Integer && properties[p].allow_nil? | |
define_method "#{p}=" do |value| | |
attribute_set(p, value == '' ? nil : value) | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment