Skip to content

Instantly share code, notes, and snippets.

@razorcd
Created March 11, 2015 18:36
Show Gist options
  • Save razorcd/c9389560c41acf7a4ec3 to your computer and use it in GitHub Desktop.
Save razorcd/c9389560c41acf7a4ec3 to your computer and use it in GitHub Desktop.
Custom model validators in Rails
#app/models/validators/valid_date_presence_validator.rb
class ValidDatePresenceValidator < ActiveModel::EachValidator
include DateHelpers
def validate_each(record, attribute, value)
unless valid_date? value
record.errors[attribute] << ('is not a valid date')
end
end
end
#app/models/sponsorship.rb
validates :start_date, valid_date_presence: true
#spec/models/sponsorship_spec.rb
#see custom Rspec matchers
it { is_expected.to have_validation ValidDatePresenceValidator, :on => :start_date }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment