I am wondering what is the canonical path in Ruby for creating custom setter and getter methods. I usually do this through attr_accessor , but I'm in the context of creating a DSL. In DSL, setters are called like this (using the = sign creates local variables):
work do duration 15 priority 5 end
Therefore, they should be implemented as follows:
def duration(dur) @duration = dur end
However, this makes the getter implementation a bit complicated: creating a method with the same name but without arguments will simply overwrite setter.
So, I wrote my own methods that perform both tuning and getting:
def duration(dur=nil) return @duration = dur if dur return @duration if @duration raise AttributeNotDefinedException, "Attribute '#{__method__}' hasn't been set" end
Is this a good way? Here is the gist with test cases:
Ruby Custom Getters and Setters
Thanks!
source share