Class: ActiveRecord::Base
- Inherits:
-
Object
- Object
- ActiveRecord::Base
- Defined in:
- lib/validates_schema/validates_schema.rb
Class Method Summary collapse
Class Method Details
.add_schema_based_validations(klass = self) ⇒ Object
inherited
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
# File 'lib/validates_schema/validates_schema.rb', line 48 def add_schema_based_validations(klass = self) klass.reset_column_information # puts klass # puts "klass.arel_table: #{klass.arel_table.inspect}" validations = [] klass.arel_table.columns.each do |c| detail = c.column next if detail.name == 'id' = {} case detail.type when :string, :text, :binary [:length] = { :maximum => detail.limit } if detail.limit.present? when :integer, :float, :decimal [:numericality] = true [:numericality] = {:only_integer => true} if detail.type == :integer end [:presence] = true unless detail.null unless .empty? validations << "validates :#{detail.name.to_sym}, #{.inspect}" klass.class_eval do validates detail.name.to_sym, || {} end end end # uncomment to see a list of generated validations: # unless validations.empty? # puts "#{klass}:" # validations.each do |line| # puts " #{line}" # end # end end |
.inherited(klass) ⇒ Object
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/validates_schema/validates_schema.rb', line 5 def inherited(klass) super(klass) begin add_schema_based_validations(klass) return # it worked, so just return rescue ActiveRecord::StatementInvalid => e # puts "e.message: #{e.message}" begin # The ActiveRecord::StatementInvalid could be a result # of an abstract superclass, so let's reset the table name # and try again: klass.reset_table_name add_schema_based_validations(klass) return # it worked, so just return rescue ActiveRecord::StatementInvalid => e # puts "e.message: #{e.message}" end end # rescue ActiveRecord::StatementInvalid # Ok, so it failed, let's add a hook around setting # the table name and try that. Hopefully all should be well then. unless klass.respond_to?(:set_table_name_with_schema_validations) klass.class_eval do class << self def set_table_name_with_schema_validations(*args) set_table_name_without_schema_validations(*args) return if abstract_class begin add_schema_based_validations(self) rescue Exception => e # apparently it just doesn't want to work, # so forget about it! # puts "e.message: #{e.message}" end end alias_method_chain :set_table_name, :schema_validations end end end end |