Ruby on rails 在调用前检查是否定义了方法/属性
我是RoR的新手。我试图找出如何检查环境文件(本例中为development.rb)中是否定义了属性 我们在development.rb文件中定义了一个属性,类似于:Ruby on rails 在调用前检查是否定义了方法/属性,ruby-on-rails,ruby,ruby-on-rails-3,ruby-on-rails-4,Ruby On Rails,Ruby,Ruby On Rails 3,Ruby On Rails 4,我是RoR的新手。我试图找出如何检查环境文件(本例中为development.rb)中是否定义了属性 我们在development.rb文件中定义了一个属性,类似于: config.user = 'test-user' 现在在代码中,我通过调用: Rails.application.config.user 这给了我所需的值 但问题是,有时可能会禁用此配置。因此,我想在分配它之前检查这个属性是否已定义。 差不多 user_name = (if Rails.application.config
config.user = 'test-user'
现在在代码中,我通过调用:
Rails.application.config.user
这给了我所需的值
但问题是,有时可能会禁用此配置。因此,我想在分配它之前检查这个属性是否已定义。
差不多
user_name = (if Rails.application.config.user is available)?
Rails.application.config.user : 'some_other_value'
我试过了?并对其作出回应,但没有起作用
欢迎提供任何帮助/建议。谢谢 如果每个环境中都定义了一个
config.user
,但有时有值,有时没有值,例如,它可能是nil
或空字符串,则可以使用:
如果未定义,则在上述情况下,您将得到一个NoMethodError
,因此您可以拯救它:
begin
user_name = Rails.application.config.user.present? ? Rails.application.config.user : 'some_other_value'
rescue NoMethodError
user_name = 'some_other_value'
end
respond\u to?
也应该起作用,只是要确保不要将它与respond\u to
混淆,因为后者是。它可能看起来像这样:
if Rails.application.config.respond_to?(:user) && Rails.application.config.user.present?
user_name = Rails.application.config.user
else
user_name = 'some_other_value'
end
如果您使用的是rails(实际上它来自于active\u support
),那么每个对象都会有一个try
方法,该方法也可以满足您的需要:
user_name = Rails.application.config.try(:user)
ruby 2.3为我们带来了&
:
user_name = Rails.application.config&.user
请注意,在这两种情况下,如果nil
不应该是有效的用户名,则可以隐式使用返回值(因为try
和&.
如果config
没有响应用户
),则将返回nil:
如果你调用这段代码超过两次(我的经验法则),你应该考虑将它提取成自己的方法,例如:代码>应用程序>用户名称>代码> < /P> 校正
在事后思考中,我认为
&.
可能不会像这里预期的那样工作,因为config
可能不是零。它实际上取决于设置(是否配置了user
但为空?如何实现config
)。我保留了答案的这一部分,因为它可能对相关问题感兴趣(但请记住:您需要ruby 2.3或更高版本)。很酷,谢谢您的回答,我以前不知道尝试。这似乎是比自己拯救异常更好的解决方案。
user_name = Rails.application.config&.user
user_name = Rails.application.config&.user || 'Guest' # ruby >= 2.3.0
user_name = Rails.application.config.try(:user) || 'Guest'