Skip to content

Instantly share code, notes, and snippets.

@rickychilcott
Created June 13, 2024 15:36
Show Gist options
  • Save rickychilcott/ffe1196535ebd610a8da82070bb14c03 to your computer and use it in GitHub Desktop.
Save rickychilcott/ffe1196535ebd610a8da82070bb14c03 to your computer and use it in GitHub Desktop.
Dynamic validations
class MyModel
include ActiveModel::Model
attr_accessor :name, :email, :options
def initialize(attributes = {})
super
@options ||= {}
end
# Class-level validations
validates :name, presence: true
validates :name, length: { minimum: :name_length, if: :validate_name_length?}
validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP }
def validate_name_length?
!!name_length
end
def name_length
options[:name_length]
end
end
puts (m = MyModel.new(name: 'John Doe', email: '[email protected]', options: {name_length: 10})).valid? # => false
puts (m2 = MyModel.new(name: 'John', email: '[email protected]', options: {name_length: 2})).valid? #= true
puts (m3 = MyModel.new(name: 'John', email: '[email protected]')).valid? #= true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment