Robert Klemme
9/2/2006 6:47:00 PM
Geoff Barnes wrote:
> Just curious, can I write a class that can check values as they are
> assigned to objects?
>
> foo = Klass.new
> foo.legal_values = (4..10)
>
> foo.value = 5 # OK
> foo.value = 11 # ERROR - out of bounds, raise exception or something
You can define a special class method as a replacement for attr_accessor:
class Module
def checked_attr(name,&test)
define_method("#{name}=") do |val|
test[val] or raise ArgumentError
instance_variable_set "@#{name}", val
end
attr_reader name
end
end
class T
checked_attr :foo do |x|
x >= 0
end
end
irb(main):018:0* t=T.new
=> #<T:0x392088>
irb(main):019:0> t.foo = 10
=> 10
irb(main):020:0> t.foo = -10
ArgumentError: ArgumentError
from (irb):4:in `foo='
from (irb):20
from :0
irb(main):021:0>
> Also, do I have to have an explicit method for the 'value', or can it
> operate like a "builtin" class, like this :
>
> foo = Klass.new
> foo.legal_values = (4..10)
>
> foo = 5 # OK
> foo = 11 # ERROR - out of bounds, raise exception or something
You cannot interfere here so there is no way to check these assignments.
> In Perl, I would probably use tiescalar for something like this, where I
> can intercept an assignment...
>
> Also, it may not be numbers, but enums as well.
I'm not sure I understand you here.
Kind regards
robert