Alle mercoledì 18 luglio 2007, Andreas Schwarz ha scritto: > Hi, > > I have a few methods that check permissions, e.g. > > unless user.can_view?(object) > puts "go away" > end > > What I want do do now is add the possibility to give the caller more > information why the user doesn't have permission. I want to make it > backwards compatible, so returning [false, NotInGroupError(:group => > 'xyz')] is not an option. The only thing I could think of is giving the > function a String or Array that is modified in place: > > def can_view?(object, message='') > if foo.bar > message.replace('some error message') > false > else > true > end > end > > That's how one would have to do it in C or VHDL. It does seem kinda > un-rubyish though. Is there some obvious way to do this better that I'm > missing? > > Thanks > Andreas I'do this: def can_view?(object, more_info = false) if foo.bar more_info ? [false, 'message'] : false else more_info ? [true, nil] : true end end If the user doesn't specify the second argument, then the method works as the original version, otherwise it returns an array whose first argument is true or false and whose second argument is nil if the user has the perimission or the reason he doesn't if he doesn't (in the example above, I used a string, but it can be anything, of course). The only drawback I can see with this approach is that you can simply test the condition using if can_view?(obj, true) #... but you need if can_view?(obj,true)[0] #... I hope this helps Stefano