Created
June 13, 2024 15:36
-
-
Save rickychilcott/ffe1196535ebd610a8da82070bb14c03 to your computer and use it in GitHub Desktop.
Dynamic validations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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