title: Ruby: Custom Implementation of attribute accessors with validation
body: <p>I'm trying to Implementation of <code>custom attribute accessors with validation</code>. </p>
  
  <p>Let say <code>attr_validated</code>. Now this <code>attr_validated</code> </p>
  
  <p><strong>1:</strong> Should have same setter and getter methods as with <a href="http://ruby-doc.org/core-2.0.0/Module.html#method-i-attr_accessor" rel="nofollow noreferrer">attr_accessor</a>. <strong>##</strong> <strong>this part is done</strong>.</p>
  
  <p><strong>2:</strong> It Should validate the given block.</p>
  
  <pre><code>attr_validated :num_legs do |v|
  v &lt;= 4
  end
  </code></pre>
  
  <p>This question might be look like any other question but its not. 
  While googled i got </p>
  
  <ul>
  <li><p><a href="https://stackoverflow.com/questions/4370960/what-is-attr-accessor-in-ruby">what-is-attr-accessor-in-ruby</a> </p></li>
  <li><p><a href="https://stackoverflow.com/questions/12790973/raising-errors-in-attribute-accessor-overrides">raising-errors-in-attribute-accessor-overrides</a></p></li>
  </ul>
  
  <blockquote>
    <p><strong>1:</strong>  Ist Part</p>
  </blockquote>
  
  <pre><code>class Class
       def attr_validated(*args)
      args.each do |arg|
        # getter
        self.class_eval("def #{arg};@#{arg};end")
        # setter
        self.class_eval("def #{arg}=(val);@#{arg}=val;end")
      end
    end
  end
  
  class Dog
    attr_validated :num_legs ## Instead of this i need to validate a block also attr_validated :num_legs do |v|
  v &lt;= 4
  end
  
  dog = Dog.new
  p dog.num_legs
  p dog.num_legs = 'Stack'
  </code></pre>
  
  <blockquote>
    <p><strong>2:</strong> How might we can Implement <strong>second part</strong>.</p>
  </blockquote>
  
  <p>Any help would be greatly appreciated !!! </p>