初期化時に 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_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
しかし、これはちょっと弱いようです。