保护子句通常是这样的:
def do_something
return 'x' if some_condition?
# other code
end
所以你的代码可以重写为
def auth_creds
return { key: 'key1', secret: 'secret1' } if %w(test1 qa demo ci).include? ENV['ENV']
return { key: 'key2', secret: 'secret2' } if ENV['ENV'] == 'live'
fail 'Unable to set key/secret'
end
但是,这很丑陋,现在 rubocop 会抱怨行太长。所以让我们改写代码来描述它的意图:
def auth_creds
return { key: 'key1', secret: 'secret1' } if test_env?
return { key: 'key2', secret: 'secret2' } if live_env?
fail 'Unable to set key/secret'
end
private # omit if `auth_creds` is also private
def test_env?
%w(test1 qa demo ci).include? ENV['ENV']
end
def live_env?
ENV['ENV'] == 'live'
end
加分项:提取%w(test1 qa demo ci)
成常数!
双倍奖励积分:(感谢@Sergio Tulentsev)从您的代码中获取特定于环境的(并且可能是敏感的!!!)凭据!如果使用 Rails,请将其放入 a 中secrets.yml
,否则请为此使用许多出色的 gem 之一:
关于 Rubocop 的一句话:对它的建议持保留态度。例如,您的代码实际上并不是保护子句的情况,它只是根据条件返回数据。因此,您也可以尝试将代码重构为case 表达式。
有时,Rubocop 只是说垃圾:-)(不是故意的,但“衡量”代码风格很难!)