I have the next code:
class Class
def attr_checked(attribute, &validation)
define_method "#{attribute}=" do |value|
raise 'Invalid attribute' unless validation.call(value)
instance_variable_set("@#{attribute}", value)
end
define_method attribute do
instance_variable_get "@#{attribute}"
end
end
end
class Person
attr_checked :age do |v|
v >= 18
end
end
bob = Person.new
bob.age = 10
p bob.age
and the error message when I am executing it:
.\example_19.rb ./example_19.rb:4:in
block in attr_checked':‘
Invalid attribute (RuntimeError)
from ./example_19.rb:23:in
Why and how can I fix it?
This is actually doing exactly what your code asks.
The attr_checked method only returns true if the block evaluates to true. Your block, returns true only if the age is greater than or equal to 18.
When you set age = 10, this block returns false and the ‘Invalid Attribute’ error is returned according to this line: