I'm trying to Implementation of custom attribute accessors with validation
.
Let say attr_validated
. Now this attr_validated
1: Should have same setter and getter methods as with attr_accessor. ## this part is done.
2: It Should validate the given block.
attr_validated :num_legs do |v|
v <= 4
end
This question might be look like any other question but its not. While googled i got
1: Ist Part
class Class
def attr_validated(*args)
args.each do |arg|
# getter
self.class_eval("def #{arg};@#{arg};end")
# setter
self.class_eval("def #{arg}=(val);@#{arg}=val;end")
end
end
end
class Dog
attr_validated :num_legs ## Instead of this i need to validate a block also attr_validated :num_legs do |v|
v <= 4
end
dog = Dog.new
p dog.num_legs
p dog.num_legs = 'Stack'
2: How might we can Implement second part.
Any help would be greatly appreciated !!!