Sravan Kumar Sravan Kumar - 2 months ago 4
Ruby Question

Check if a method/property is defined or not before calling

I am a newbie to RoR. I am trying to figure out how to check if a property is defined or not in the environment file(development.rb in this case).

We have a property defined in development.rb file, something like:

config.user = 'test-user'

Now in the code, I use it by calling:


which gives me the required value.

But the problem is this configuration may be disabled sometimes. So, I want to check if this property is defined or not before assigning it.
Something like

user_name = (if Rails.application.config.user is available)?
Rails.application.config.user : 'some_other_value'

I tried defined? and respond_to but did not work.

Any help/suggestions are appreciated. Thanks!


If there is a config.user defined in every environment, but sometimes it has a value, and sometimes it doesn't, for example, it could be nil or an empty string, you can use present?:


If it is not defined, you will get a NoMethodError in the case above, so you can rescue it:

  user_name = Rails.application.config.user.present? ? Rails.application.config.user : 'some_other_value'
rescue NoMethodError
  user_name = 'some_other_value'

respond_to? should also work, just make sure you don't confuse it with respond_to, which is a Rails method. It might look something like this:

if Rails.application.config.respond_to?(:user) && Rails.application.config.user.present?
  user_name =  Rails.application.config.user
  user_name = 'some_other_value'