title: Ruby get and set in one method
body: <p>I'm wondering what's the canonical way in Ruby to create custom setter and getter methods. Normally, I'd do this via <code>attr_accessor</code> but I'm in the context of creating a DSL. In a DSL, setters are called like this (using the <code>=</code> sign will create local variables):</p>
  
  <pre><code>work do
   duration 15
   priority 5
  end
  </code></pre>
  
  <p>Therefore, they must be implemented like this:</p>
  
  <pre><code>def duration(dur)
   @duration = dur
  end
  </code></pre>
  
  <p>However this makes implementing a getter a bit tricky: creating a method with the same name but with no arguments will just overwrite the setter. </p>
  
  <p>So I wrote custom methods that do both the setting and the getting:</p>
  
  <pre><code>def duration(dur=nil)
   return @duration = dur if dur
   return @duration if @duration
   raise AttributeNotDefinedException, "Attribute '#{__method__}' hasn't been set"
  end
  </code></pre>
  
  <p>Is this a good way to go about it? Here's a gist with test cases:</p>
  
  <p><a href="https://gist.github.com/3033911" rel="nofollow">Ruby Custom Getters &amp; Setters</a> </p>
  
  <p>Thanks!</p>