分配分支条件太高

Assignment Branch Condition too high

我有一个简单的 class,它在初始化时需要一到八个参数。它将访问器设置为这些访问器以供以后使用。 Rubocop 正试图以 ABC 太高为由逮捕我,但我不确定我所做的是否真的有任何问题。这是我在初始化时禁用检查的情况吗?

class Foo
  attr_accessor :one, :two, :three, :four
  attr_accessor :five, :six, :seven, :eight

  def initialize(p={})
    @one = p[:one] if p[:one].present?
    # ...
    @eight = p[:eight] if p[:eight].present?
  end
end

我对减小大小的唯一想法是做一些事情,比如在初始化时遍历我所有的 attr_accessors,看看 has 中是否有相应的符号通过,如果是,则分配它。

class Foo
  attr_accessor :one, :two, :three, :four
  attr_accessor :five, :six, :seven, :eight

  def initialize(p={})
    instance_variables.each do |variable|
      send("@#{variable}") = p["#{send(variable)}".to_sym] if p["#{send(variable)}".to_sym].present?
    end
  end
end

但这似乎有点弱。

这是实现您想要做的事情的方法之一:

class Foo
  attr_accessor(*%i[one two three four five six seven eight])

  def initialize(p = {})
    p.keys.each { |k| instance_variable_set("@#{k}", p.fetch(k, nil)) }
  end
end

查看 Hash#fetch 方法。

您也可以使用它来访问 key-value 对 p 变量,如果您决定使用一个 (@p)[=21= 而不是 8 个变量]


编辑

出于好奇写了这个版本(使用了一些元编程)——它会动态添加 attr_accessor 以添加实例变量:

class Foo
  def initialize(p = {})
    p.keys.each do |k|
      instance_variable_set("@#{k}", p.fetch(k, nil))
      self.class.__send__(:attr_accessor, k)
    end
  end
end

发生了什么,我们获取提供给 initialize 方法参数(散列 p),获取它的键并从中创建实例变量,为每个变量分配与键对应的值。然后我们为每个键定义 attr_accessor

a = Foo.new(a: 2, b: 3)
#=> #<Foo:0x00000002d63ad8 @a=2, @b=3>

您不应将其中的每一个分配为不同的变量。您应该将其作为单个散列保存到变量中,并在需要值时访问散列。事实上,你似乎已经有了一个变量p。所以保持为 @p = p.