Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

added friday

  • Loading branch information...
commit f8714bb2f5899a114032e845b34830c2121f5f0c 1 parent bc8a90d
@honkimi authored
Showing with 45 additions and 0 deletions.
  1. +45 −0 metaprogrammingruby/friday.rb
View
45 metaprogrammingruby/friday.rb
@@ -0,0 +1,45 @@
+require 'test/unit'
+
+module CheckedAttributes
+ def self.included(base)
+ base.extend(ClassMethods)
+ end
+ module ClassMethods
+ def attr_checked(attribute, &validate)
+ define_method "#{attribute}" do
+ instance_variable_get "@#{attribute}"
+ end
+ define_method "#{attribute}=" do |value|
+ raise 'Invalid attribute' unless validate.call(value)
+ instance_variable_set("@#{attribute}", value)
+ end
+ end
+ end
+end
+
+class Person
+ include CheckedAttributes
+ attr_checked :age do |v|
+ v >= 18
+ end
+end
+
+class TestCheckedAttribute < Test::Unit::TestCase
+ def setup
+ @bob = Person.new
+ end
+
+ def test_accepts_valid_values
+ @bob.age = 20
+ assert_equal 20, @bob.age
+ end
+
+ def test_refuses_nil_values
+ assert_raises RuntimeError, 'Invalid attribute' do
+ @bob.age = 17
+ end
+ end
+
+end
+
+
Please sign in to comment.
Something went wrong with that request. Please try again.