ruby’s respond_to? for checking if a method exists

October 16th, 2007 by Prateek Dayal | Print ruby’s respond_to? for checking if a method exists

Ruby has a function called respond_to? that can be used to seeing if a particular class or object has a method with a certain name. The syntax is something like


User.respond_to?('name') # returns true is method name exists otherwise false

This came in very handy the other day when I wanted to send emails in muziboo to people whenever they get a reply for either their posts, or a comment on their song or other stuff. Since I am using acts_as_commentable for all commenting, I added this to comments.rb (model)

after_create
if commentable.respond_to?('notify_comment')
commentable.notify_comment()
end
end

Now every model, for which I wanted to send an email (when a new comment is added), i defined notify_comment() function and called UserNotifier.deliver_xxx method inside that. For models where I did not want to send an email, I never defined the function and everything worked fine because respond_to? will return a false for those models

The above really helped me simplify the controller code and keep the code consistent. Thought of sharing this with everyone. Please do leave your comments if something is not quite right :)

Popularity: 52% [?]

 

4 Comments

  1. AR

    Nice tip. pretty handy and reflects explanation of ruby’s duck typing feature.

  2. Thank you, this was useful to me.

  3. Kamal Nandan

    Hi Prateek,

    I saw read your profile and got to know that you have developed your site in RoR. I am in the process of developing a website and I am perplexed whether I must develop that in PHP or CakePHP or RoR.; though I would prefer RoR I have a few questions on RoR:
    1. I am basically a technical person and have been developing in C/C++, Unix. If I want to develop the site on my own, then i need to learn RoR. So how long should it take to learn RoR and get a basic website up and running?
    2. Since time is a very critical factor, will it be easier and faster to learn and implement in PHP or CakePHP?
    3. Is it possible to get a hosting solution provider for RoR portal in India? If yes, does it cost significantly higher than what it costs in case of PHP?

    Your reply would help me significantly in going ahead with my venture.

    Thanks & Regards,
    Kamal

  4. Почему это вдруг эксклюзивно так? Я считаю, как можно прояснить данную гипотезу.

Trackbacks

Leave a Reply

Additional comments powered by BackType