Alien Life Form Alien Life Form - 1 year ago 62
Ruby Question

How do I check if a Rails.application.config variable is defined?

Even though

returns a full array,
returns nil.

Rails.application.config.trackable_models # => ["NewsItem", "ContentPage", "Event"]
defined?(Rails.application.config.trackable_models): # => nil

Setting a local variable in the same way is fine:

foo = ["x"]
defined?(foo) # => local-variable

What is the proper way to check for the existence of a config variable if not "defined?"?

Answer Source

If you want to check the method is defined in the literal sense, use respond_to


If you want to check if the method returns something other than nil, you have some options:

tm = Rails.applications.config.trackable_models
tm.presence || 'default value'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download