标签: ruby-style-guide

如何在ruby中重构长字符串行的最佳方法?

我有一行像这样的代码

"#{envelope_quantity} - envelope #{Budget::util_name(envelope_size)} #{Budget::util_name(envelope_paper)} #{Budget::util_name(envelope_color)} #{Budget::util_name(envelope_grammage)} #{Budget::util_name(envelope_model)} #{Budget::util_name(envelope_print)}"
Run Code Online (Sandbox Code Playgroud)

太长了,读起来很糟糕,这就是为什么RuboCop用它的Metrics :: LineLength警告我的原因.

我想重构它不是一个长队.

我知道有很多方法可以做到这一点,但我想知道哪一个是红宝石风格专家的预期.

当我需要一个空字符串时,如果它是nil,则需要静态方法util_name来防止nil.

def self.util_name(value)
  return '' if value.nil?
  value.name
end
Run Code Online (Sandbox Code Playgroud)

ruby ruby-on-rails ruby-on-rails-4 ruby-style-guide

4
推荐指数
2
解决办法
2250
查看次数

使用`Object#send`方法作为最佳实践

很难识别代码的用法,如下所示:

[:create, :update, :pause].each { |action| send("to_#{action}") }
Run Code Online (Sandbox Code Playgroud)

这是一个反模式还有其他原因吗?

ruby ruby-style-guide

1
推荐指数
1
解决办法
260
查看次数

Rubocop JSON:如果方法调用的参数跨越多行,则对齐它们

我在测试文件中遇到了 Rubocop 问题。起初,这是我现在的代码:

should 'should show user' do
  get user_url(@user),
    headers: @header
  assert_response :success
end

should 'should update user' do
  patch user_url(@user),
    params: {
      data: {
        attributes: {
          name: @user.name
        }
      }
    }, headers: @header
  assert_response :success
end
Run Code Online (Sandbox Code Playgroud)

这就是 Rubocop 错误输出:

test/controllers/users_controller_test.rb:34:9: C: Align the parameters of a method call if they span more than one line.
        headers: @header
        ^^^^^^^^^^^^^^^^
test/controllers/users_controller_test.rb:40:9: C: Align the parameters of a method call if they span more than one line.
        params: { ...
        ^^^^^^^^^ …
Run Code Online (Sandbox Code Playgroud)

ruby json ruby-on-rails rubocop ruby-style-guide

1
推荐指数
1
解决办法
5640
查看次数