[英]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
返回完整的数组, defined?(Rails.application.config.trackable_models)
返回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?"? 如果未“定义”,检查配置变量是否存在的正确方法是什么?
If you want to check the method is defined in the literal sense, use respond_to
如果要检查按字面意义定义的方法,请使用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: 如果要检查该方法是否返回nil
以外的值,则可以使用以下选项:
tm = Rails.applications.config.trackable_models
tm.nil?
tm.presence || 'default value'
tm.present?
tm.blank?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.