Skip to content

Instantly share code, notes, and snippets.

@snusnu
Created January 26, 2010 22:40
Show Gist options
  • Save snusnu/287322 to your computer and use it in GitHub Desktop.
Save snusnu/287322 to your computer and use it in GitHub Desktop.
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