Skip to content

Instantly share code, notes, and snippets.

@Andrew8xx8
Created February 5, 2019 08:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Andrew8xx8/659722bc128432bc3e56c28f96838844 to your computer and use it in GitHub Desktop.
Save Andrew8xx8/659722bc128432bc3e56c28f96838844 to your computer and use it in GitHub Desktop.
Ruby DSL
class A
def self.validates(attribute, options)
p 'define validator', attribute, options
@@validatos ||= {}
@@validatos[attribute] = options
p '/define validator'
end
def valid?
@@validatos.keys.map do |attribute|
validate_options = @@validatos[attribute]
if validate_options[:length]
validate_length(attribute, validate_options[:length])
else
true
end
end.reduce(:and)
end
def validate_length(attribute, options)
value = send(attribute)
value.size > options[:minimum]
end
end
class B < A
attr_accessor :foo
validates :foo, length: { minimum: 2 }
def initialize(attrs)
@foo = attrs[:foo]
end
end
b = B.new(foo: 'a')
p 'Not Valid', b.valid?
b = B.new(foo: 'asda')
p 'Valid', b.valid?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment