the following code works but i wanted to run it past someone since i'm in
new territory here.
the goal here is basically to provide declarations similar to
attr_reader/_writer that provide 1) default values when the property is nil
and 2) enforced preconditions to setters.
code >>
class Module
def attr_default(symbol, default)
default = "'#{default}'" if default.type == String
module_eval "def #{symbol}() if @#{symbol}.nil?; #{default}; else
@#{symbol}; end; end"
end
def attr_filter(symbol, *filters)
filtered_setter = "def #{symbol}=(value) "
filters.each { |f|
filtered_setter += " value=#{f}(value);"
}
filtered_setter += " @#{symbol}=value; end"
module_eval filtered_setter
end
end
class Cat
attr_default :meow, 'x'
attr_filter :meow, :stripVowels, :stripRs
def stripVowels(s)
s.gsub!(/[aeiou]/, '.')
end
def stripRs(s)
s.gsub!(/r/, '_')
end
end
cat = Cat.new();
puts cat.meow;
cat.meow = "arf";
puts cat.meow;
<<
output >>
x
._f
<<
am i sane?