我有一个简单的类,在初始化时,需要一到八个参数.它将访问器设置为稍后使用.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
Run Code Online (Sandbox Code Playgroud)
我对减小大小的唯一想法是做一些事情,比如在初始化时迭代我的所有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
Run Code Online (Sandbox Code Playgroud)
但这似乎有点弱.
我有一些看起来类似于此的代码:
foo = SomeActiveRecordModel.where(bar: 10).first.foo rescue ''
Run Code Online (Sandbox Code Playgroud)
一旦我开始使用Rubocop,就会在那里大吼大叫救援语法.所以我认为至少有两种方法可以编写这些代码:
foo =
begin
foo = SomeActiveRecordModel.where(bar: 10).first.foo
rescue NoMethodError
''
end
Run Code Online (Sandbox Code Playgroud)
和:
foo = SomeActiveRecordModel.where(bar: 10).first
foo.present? ? foo.foo : ''
Run Code Online (Sandbox Code Playgroud)
哪种方式更受欢迎,或者是否有其他首选方式?