Daniel Schierbeck
4/1/2006 3:59:00 PM
Daniel Schierbeck wrote:
> I couldn't find a Facets mailing list, and I know the developers use
> this list, so therefore I send my proposal here.
>
> I'd like to see the addition of an attribute validator, i.e. a setter
> that checks to see if a block returns true when called with the new
> value as its only argument. Without further ado, I hereby present
> Module#attr_validator:
>
> class Module
> def attr_validator(*symbols, &validator)
> symbols.each do |symbol|
> define_method "#{symbol}=" do |val|
> unless validator.call(val)
> raise ArgumentError, "Invalid value provided for #{symbol}"
> end
> instance_variable_set("@#{symbol}", val)
> end
> end
> end
> end
>
> Use it, change it, polish it - it's yours.
>
>
> Cheers,
> Daniel Schierbeck
Note that this of course only works when you actually *use* the setter
method, i.e. `@attr = val' will not validate `val'. Nor do I think it
should.
Cheers,
Daniel Schierbeck