Rails 中的蓝图序列化程序自定义字段中的 Rubocop 警告 SymbolProc

Rubocop warning SymbolProc in blueprinter serializer custom field in Rails

我有一个带有自定义字段的 Blueprinter 序列化程序(见屏幕截图)

field :score_details do |user|
  user.score_details
end

你可以看到这个块的 Rubocop 警告,我不能让它消失。我阅读了 Rubocop 文档:SymbolProc 但没有成功..

详细解释:我有一个用户模型,其中包含一个关注点以计算分数。在这个问题上,我有 1 种方法(没有参数),其中 returns 是一个简单的整数。 最后,我在我的 UserSerializer 中使用了这个方法,以便将我的分数呈现到我的前端。

这是我的用户模型中的内容:

class User < ApplicationRecord
  include UserScoresConcern
end

这是我的担忧:

module UserScoresConcern
  extend ActiveSupport::Concern

  included do
    def score_details
      # this method return 45 for example
      calculate_user_score_details
    end
  end
end

如何解决此警告?有没有人遇到过同样的问题?

谢谢

你只需要写成

field :score_details, &:score_details

原因是&前缀运算符接受它的参数(在本例中是一个符号),调用它的to_proc方法,确保它实际上是一个proc,然后使用它作为块参数。

对于符号,to_proc 方法 returns 一个单参数过程,相当于参数上的 __send__ 方法。即:

# these are functionally equivalent:
:my_symbol.to_proc
->(arg) { arg.__send__(:my_symbol) }
->(arg) { arg.my_symbol }

区别在于 Symbol#to_proc 可以说是更优化了。

我设法让它工作,但没有自定义字段。

我像那样将我的方法直接添加到我的字段列表中并且有效:

fields  :email,
        :score_details

field 方法采用一个块,该块将使用 objectlocal_options 两个参数调用。 See BlockExtractor#extract

你的问题是你的块忽略了提供 2 个参数的事实,因此 Rubocop 认为你可以使用 Symbol#to_proc(因为它认为只有一个参数发送到块);但是,如果您确认第二个参数,则此警告将消失。

field :score_details do |user,_| 
  user.score_details
end

这里我们使用下划线字符 _ 确认第二个参数。这是表明我们不打算使用此参数的标准约定。

另一种确定方法是使用 2 个参数调用块的方法是改用 lambda

field :score_details, &->(user) {user.score_details}

这将导致 ArgumentError (wrong number of arguments (given 2, expected 1)),因为 lambda 只需要 1 个参数,但传入了 2 个参数。这是标准 Proc 和 lambda (这是 Proc).

的“特殊”类型

您遇到的错误 “错误的参数数量(给定 1,预期 0)” 可以很容易地重新创建以显示实际发生的情况

def example
  yield "10",2
end 

example(&:to_s)
ArgumentError (wrong number of arguments (given 1, expected 0))

这是因为在这种情况下使用 Symbol#to_proc 时,它将计算为 "10".to_s(2)String#to_s 不会像 User#score_details 那样接受任何参数,因此导致 user.score_details(local_options) 以同样的方式失败。