Created
February 4, 2009 03:27
-
-
Save itstommymorgan/57907 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
module ValidatedAccessor | |
# Usage: | |
# | |
# class Foo | |
# include ValidatedAccessor | |
# attr_validated_accessor(:bar, :baz) { |x| x.between? 1, 10 } | |
# end | |
# | |
# f = Foo.new | |
# f.bar = 5 | |
# f.bar = 12 <-- Exception! | |
def attr_validated_accessor(*syms, &block) | |
raise 'Validation criteria in block required' unless block | |
syms.each do |sym| | |
module_eval do | |
# Give us a standard reader. | |
attr_reader sym | |
# Define a writer that's special. | |
define_method("#{sym}=") do |value| | |
raise ArgumentError if !block.call(value) | |
instance_variable_set "@#{sym}", value | |
end | |
end | |
end | |
# Return nil from the attr_validated_accessor call. | |
nil | |
end | |
end | |
# Test it out! | |
class Foo | |
include ValidatedAccessor | |
attr_validated_accessor(:bar, :baz) { |x| x.between? 1, 10 } | |
end | |
f = Foo.new | |
f.bar = 1 | |
f.baz = 2 | |
puts f.bar | |
puts f.baz | |
begin | |
f.bar = 11 | |
rescue ArgumentError | |
puts 'Got an argument error' | |
end | |
begin | |
f.baz = -1 | |
rescue ArgumentError | |
puts 'Got another argument error' | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment