From: Daniel Schierbeck Date: 2006-04-02T23:23:44+09:00 Subject: Re: Add a Module#attr_validator method Trans wrote: > Thanks Daniel, I'll give this some consideration. > > A more interesting alternative that could soon come to pass is an > extension to Facets' annotation system. Right now one can easily do: > > require 'facet/annotation' > > class Foo > attr_accessor :x > ann :x, :validation => proc { |x| ... } > end > > But this is nothing more than a note. For it to actually have any > effect one would have to manually utilize the note. With then next > version of annotation.rb I plan to add annotation hooks. By defining a > hook you can automatically have it do what you would like when a > particular annotation is define. For instance: > > Annotation.annotation_action( :validation ) { |symbol, validator| > wrap_method( "#{symbol}=") { |target, x| > unless validator.call( x ) > raise ArgumentError, "Invalid value provided for #{symbol}" > else > target.call(x) > end > } > } > > Now when you make the above annotation it will automatically generate > the validating setter as you describe. > > The only downside to this kind of thing at the moment is the lack of an > adequate AOP foundation built into Ruby. > > But all that is down the road yet. In the mean time I will likely add > your method. Thanks. > > T. > > P.S. Using this list is fine, especially if you're interested in wider > input from the Ruby community. You can also email the Nitro list > --Facets is a key component of Nitro/Og. And of course you can always > email me directly. Thanks for considering my idea. Personally, I like to think of a validator as a setter/writer that adds value validation - annotations just don't fit in my perception of that process, though what you describe would be useful, too. Cheers, Daniel Schierbeck