Showing posts with label object. Show all posts
Showing posts with label object. Show all posts

Saturday, May 9, 2009

Ruby trick

For those who are trapped into the same problem as I am.

obj.atr

Block below is valid for the block above:

def x(obj, atr)
    return obj.send(:atr)
end

Have fun! Please, let me know how will you use this code, if you find it useful at all. In example, I can see that it can be used for something like this:

p User.find(:first, :condition => {:userid => 1}).name

This will drop an exception, if there is no such user with id 1. However, you can call it through the wrapper:

def wrp(obj, atr)
  if obj.nil?
  then
    return "N/A"
  else
    return obj.send(:atr)
  end
end
 
...
 
p wrp(User.find(:first, :condition => {:userid => 1}), name)

This might be awkward, but works well enough.

P.S. Here is the original question posted in Twitter and replies to it. (Thanks to Tweeplies.)