Harshit Laddha
Harshit Laddha

Reputation: 2124

How do I check if a method exists and returns some value or not in Ruby?

I am using a google drive api, where I am fetching a file object from the google drive api. Now that file may/may not have the downloadLink and the webContentLink depending on the user authenticating the file. Now I have these methods where

download_links[index][1] = i.webContentLink if i.responds_to? :webContentLink

Now it says responds_to is not defined for i. Now i is a remote object, so i cannot change its implementation and add method_missing or responds_to method. so how do i check if i.webContentLink is a valid method or not in that ith object.

Upvotes: 0

Views: 320

Answers (1)

kik
kik

Reputation: 7937

There are two things, here.

First, #responds_to? indeed does not exist, anywhere :) The correct method name for what you want to use is #respond_to?.

Secondly, this is not a ruby method as you ask for it, but I mention it since you post your question with ruby on rails tag. ActiveSupport, from rails, implements a #try method to do that.

It will return the result of the method if it exists, or nil :

download_links[index][1] = i.try( :webContentLink )

Be sure not to abuse that, as it quickly leads to hard to understand code (at some point, you will want to learn about NullObjects).

Upvotes: 4

Related Questions