Alien Life Form Alien Life Form - 3 months ago 10
Ruby Question

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

Even though

Rails.application.config.trackable_models
returns a full array,
defined?(Rails.application.config.trackable_models)
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

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

Rails.applications.config.respond_to?(:trackable_models)

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

tm = Rails.applications.config.trackable_models
tm.nil?
tm.presence || 'default value'
tm.present?
tm.blank?
Comments