Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Without having looked much at your code, here's my take on implementing validation class methods:</p> <pre><code>module Validations def self.included(base) base.extend ClassMethods end def validate errors.clear self.class.validations.each {|validation| validation.call(self) } end def valid? validate errors.blank? end def errors @errors ||= {} end module ClassMethods def validations @validations ||= [] end def validates_presence_of(*attributes) validates_attributes(*attributes) do |instance, attribute, value, options| instance.errors[attribute] = "cant't be blank" if value.blank? end end def validates_format_of(*attributes) validates_attributes(*attributes) do |instance, attribute, value, options| instance.errors[attribute] = "is invalid" unless value =~ options[:with] end end def validates_attributes(*attributes, &amp;proc) options = attributes.extract_options! validations &lt;&lt; Proc.new { |instance| attributes.each {|attribute| proc.call(instance, attribute, instance.__send__(attribute), options) } } end end end </code></pre> <p>It assumes that ActiveSupport is around, which it is in a Rails environment. You might want to extend it to allow multiple errors per attribute, with <code>instance.errors[attribute] &lt;&lt; "the message"</code>, but I left out obscurities like that in order to keep this short sample as simple as possible.</p> <p>Here's a short usage example:</p> <pre><code>class MyClass include Validations attr_accessor :foo validates_presence_of :foo validates_format_of :foo, :with =&gt; /^[a-z]+$/ end a = MyClass.new puts a.valid? # =&gt; false a.foo = "letters" puts a.valid? # =&gt; true a.foo = "Oh crap$(!)*#" puts a.valid? # =&gt; false </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload