0

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?

1
  • Isn't it doing precisely what you want? You're validating that age is >= 18, and then you use an age of 10 and an exception is raised. What's surprising? Commented Mar 20, 2012 at 8:27

1 Answer 1

1

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.

attr_checked :age do |v|
        v >= 18
end

When you set age = 10, this block returns false and the 'Invalid Attribute' error is returned according to this line:

raise 'Invalid attribute' unless validation.call(value)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.