Skip to content

Commit

Permalink
Ability to pass in options to validators
Browse files Browse the repository at this point in the history
  • Loading branch information
tmikoss committed Jul 11, 2012
1 parent 420637c commit d6068e6
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 3 deletions.
16 changes: 13 additions & 3 deletions lib/automagical_validations.rb
@@ -1,11 +1,21 @@
module AutomagicalValidations
def automagically_validate(*types_to_validate)
return unless self.table_exists?
types_to_validate.map!{ |type| type.to_sym }

validation_settings = {}

if types_to_validate.first.is_a? Hash
validation_settings = types_to_validate.first
validation_settings.symbolize_keys!
else
types_to_validate.each do |type|
validation_settings[type.to_sym] = {}
end
end

columns.each do |column|
# Do not touch the columns not specified
next unless types_to_validate.include? column.type
next unless validation_settings[column.type]

# Do not define validator on columns that have no limit information, even if asked to
next unless column.limit
Expand All @@ -15,7 +25,7 @@ def automagically_validate(*types_to_validate)
validator.is_a?(ActiveModel::Validations::LengthValidator) && validator.options[:maximum]
end

validates_length_of column.name, :maximum => column.limit
validates_length_of column.name, validation_settings[column.type].merge({:maximum => column.limit})
end
end
end
Expand Down
21 changes: 21 additions & 0 deletions spec/automagical_validations_spec.rb
Expand Up @@ -173,5 +173,26 @@
end
end
end

context "passing options to validator" do
let(:validator_options){ {:message => 'Custom message'} }

before(:all) do
Post.rebuild_table do |t|
t.string :title
t.text :content
end

Post.automagically_validate :string => validator_options
end

it "should define validator" do
Post.should have(1).validators_on(:title)
end

it "should define options for validator" do
Post.validators_on(:title).first.options[:message].should eq validator_options[:message]
end
end
end
end

0 comments on commit d6068e6

Please sign in to comment.