From: Rick DeNatale Date: 2007-12-08T00:37:30+09:00 Subject: Re: Worth an RCR? static_type_check, polymorphic_type_check, On 12/7/07, MonkeeSage wrote: > On Dec 7, 7:09 am, Rick DeNatale wrote: > > I came across another interesting example from ActiveRecord, as I was > > reading myself to sleep early this AM with "The Ruby Way." > > > > There's a method ActiveRecord::Base#save which is used to, surprise, > > save/update an AR model instance to the database. This method is > > documented as taking no arguments. > > > > BUT > > > > Under some circumstances, you can call the method with an optional > > argument as in: > > > > book.save(false) > > > > Which causes the object to be saved bypassing any validation callbacks. > > > > It turns out that the save method will only take the argument if the > > model has one or more validations specified. The method signature > > changes dynamically. > > > > While I can see these kind of things frustrating, or even angering > > chicken typers, the are the very things which make Ruby magical. > That's also a great use case for what I was talking about in my last > post. ;) An #arity < 1 check might be nicely used in such a case to > check whether to call #save with an argument, and if not, do something > else, rather than letting the exception raise, catching it, then doing > something else. Either way works (though catching the exception is > probably less efficient, because an exception object has to be > instantiated and the rescue machinery has to run); but in cases like > that, it makes perfect sense to do "validation" on the object. (Even > if it arities like a chicken right now...it's still really a duck ;P) But that kills the duck. Think about how this is used in ActiveRecord/Rails. In most cases you want to save and run validations, using save with no parameter works fine, note that the argument, when it's supported, has a default value of true which causes the validations to be run. In some particular cases, you want to overrule validations because you know what you are doing. You know that the model has validations, and you know you want to override them in this case. The best way to validate this knowledge is with test cases rather than burdening the production code with unnecessary overhead. IMHO, chicken typing is for Chicken Littles, who worry too much about exactly what exception would be raised if the sky actually fell. -- Rick DeNatale My blog on Ruby http://talklikeaduck.denhaven2.com/