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?