2012-03-20 98 views
0

我有下一個代碼:執行塊錯誤

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 

並且當我在執行它的錯誤消息:

\ example_19.rb ./example_19.rb:4:in block in attr_checked': Invalid attribute (RuntimeError) from ./example_19.rb:23:in '

爲什麼以及如何解決?

+0

這不正是你想要的嗎?您正在驗證該年齡≥18,然後您使用10歲,並且引發異常。什麼令人驚訝? – 2012-03-20 08:27:33

回答

1

這實際上正在完成您的代碼要求。

attr_checked方法只在塊的計算結果爲true時才返回true。你的塊,返回true只有在年齡大於或等於18

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

當您設置根據這條線年齡= 10,此塊返回false並返回「無效屬性」錯誤:

raise 'Invalid attribute' unless validation.call(value)