Skip to content

Instantly share code, notes, and snippets.

@gregoriokusowski
Created February 21, 2011 14:23
Show Gist options
  • Save gregoriokusowski/837113 to your computer and use it in GitHub Desktop.
Save gregoriokusowski/837113 to your computer and use it in GitHub Desktop.
a rails model used to create all "validates_numericality_of" validations based on the schema. The code sux a bit, and have a lot of smells, but is working by now...
class TheModel
def name
@model_name
end
def initialize(line)
@model_name = extract_name(line).to_s.singularize
end
def add(line)
if has_integer? line
(@integers ||= []) << extract_name(line)
elsif has_decimal? line
(@decimals ||= []) << extract_decimal(line)
end
end
def to_s(abc = nil)
puts %(#{@model_name}
.... @integers = #{@integers.inspect}
.... @decimals = #{@decimals.inspect})
end
def integer_validation
"validates_numericality_of #{@integers.to_s[1..-2]}, :allow_nil => true" if has_integers?
end
def decimal_validation
"validates_numericality_of #{@decimals.collect{|i| i[:column]}.to_s[1..-2]}, :allow_nil => true, :less_than => 100000000" if has_decimals?
# if @decimals
# # @inverted = @decimals.invert
# # @inverted.
# end
end
def has_anything?
has_integers? or has_decimals?
end
def self.is_table(line)
line =~ /create_table/
end
def self.is_allowed(line, to_skip)
to_skip.none?{|w| /#{w}/ =~ line}
end
def remove(property)
@decimals.delete(property) if @decimals
@integers.delete(property) if @integers
end
private
def has_integers?
@integers and [email protected]?
end
def has_decimals?
@decimals and [email protected]?
end
def has_integer?(line)
line =~ /\.integer/
end
def has_decimal?(line)
line =~ /\.decimal/
end
def extract_name(line)
line.gsub( /"(.*)"/ ).first.gsub(/"/, "").to_sym
end
def extract_decimal(line)
{:column => extract_name(line),
:options => eval("{#{line.gsub( /:.*$/ ).first}}")}
end
end
class Runner
def self.run
schema_path = "db/schema.rb"
models_folder_path = "app/models"
to_skip = %w(session)
f = File.open(schema_path)
while (l = f.gets)
#change me :/
if TheModel.is_table(l) and TheModel.is_allowed(l, to_skip)
@last_model = TheModel.new(l)
(@models ||= []) << @last_model
end
@last_model.add(l) if @last_model
end
@models.each do |m|
m.name.camelize.constantize.validators.each do |validator|
if validator.is_a? ActiveModel::Validations::NumericalityValidator
validator.attributes.each do |validator_attribute|
m.remove(validator_attribute)
end
end
end
@models.delete(m) unless m.has_anything?
end
@models.each do |m|
File.open("#{models_folder_path}/#{m.name}.rb", 'r+') do |f|
out = ""
f.each_with_index do |line, index|
if index == 2
out << " #{m.integer_validation}\n" if m.integer_validation
out << " #{m.decimal_validation}\n" if m.decimal_validation
end
out << line
end
f.pos = 0
f.print out
f.truncate(f.pos)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment