Skip to content

Instantly share code, notes, and snippets.

@benfyvie
Created June 10, 2011 17:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benfyvie/1019294 to your computer and use it in GitHub Desktop.
Save benfyvie/1019294 to your computer and use it in GitHub Desktop.
automatically add generic validations to all models
module ActiveRecord::Validations::ClassMethods
#inspired by rails-schema_validations
#https://github.com/gregwebs/rails-schema-validations
def add_generic_validations
begin
self.columns.map do |column|
case column.type
when :date
validates_format_of_date(column.name) #this is a custom validation we defined (not part of rails)
end
end.compact
rescue ActiveRecord::StatementInvalid => e
#We may get an exception if the model uses the #set_table_name macro method because at this point of the model initialization
#it doesn't yet have the correct table name to when it calls self#columns it is going to call it against the wrong table.
#However this isn't that big of a deal because we have also aliased #set_table_name so that when it is called we will
#re-run #validations_from_schema so that it will be run using the correct table name
raise unless e.message =~ /relation "#{self.table_name}" does not exist/
end
end
end
ActiveRecord::Base.class_eval do
class << self
#enforce generic data type validations all the time on all models
def inherited(subclass) #called when ActiveRecord::Base is inherited by another class...exactly what we need to add this functionality to all of our models
super
subclass.class_eval do
add_generic_validations
end
end
alias_method :old_set_table_name, :set_table_name
def set_table_name(new_name)
old_set_table_name(new_name)
add_generic_validations
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment