我有一个简单的类,在初始化时需要1到8个参数。它将这些访问器设置为以后使用。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_accessor,查看是否在哈希表中有对应的符号,并将其赋值。
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
但这似乎有些虚弱。
ATTR_NAMES = %i(one two three four five six seven eight).freeze
常量,并调用attr_accessor(*ATTR_NAMES)
。 - chad_