-1

I wonder, is there any way to make the following code simpler?

  def my_filer model_names
      model_names.keep_if { |x| not x.empty? }
      unless model_names.empty?
        where 'model_name_field in (?)', model_names
      else
        self
      end
  end
4

4 回答 4

2
def my_filter model_names
  model_names = model_names.to_a.select(&:present?)
  model_names.present? ? where( :model_name_field  => model_names) : self
end

Note: Rails converts the array value to IN statement when you use hash notation for where clause.

于 2013-07-23T06:18:19.443 回答
1

What about this

def my_filer model_names
  model_names.reject!(&:empty?)
  if model_names.empty?
    self
  else
    where 'model_name_field in (?)', model_names
  end
end
于 2013-07-23T06:01:24.277 回答
1

This is "simpler", but IMO, it's less readable. I'd suggest you use the more-verbose-and-easy-to-understand version, personally.

def my_filer(model_names)
  return self if (names = Array(model_names).reject(&:empty?)).empty?
  where 'model_name_field in (?)', names
end
于 2013-07-23T06:13:16.920 回答
1
def my_filer model_names
  model_names.reject!(&:empty?)
  model_names.empty? ? self : where 'model_name_field in (?)', model_names
end

Not simpler, but a different form.

Or you could use the && and || for expressing the ternary.

Perhaps less commonly used, is the and and or operators.

于 2013-07-23T06:19:44.310 回答