0

这是代码:

def explaination_exists
explaination_exists_flag = false
if self.explanation1.length > 5
  explaination_exists_flag = true 
end
if self.explanation2.length > 5
  explaination_exists_flag = true 
end
if self.explanation3.length > 5
  explaination_exists_flag = true 
end
if self.explanation4.length > 5
  explaination_exists_flag = true 
end

unless explaination_exists_flag
  errors.add(:base, 'Atleast one explanation should be there.')
end
end

我想将代码简化为单行代码,因为除了说明[编号]之外没有任何变化。

我试过这个:

 def explaination_exists
 explaination_exists_flag = false
 (1..4).each do |i| 
  if self."explanation#{i}".to_sym.length > 5 
  explaination_exists_flag = true
  break 
  end
end
unless explaination_exists_flag
  errors.add(:base, 'Atleast one explanation should be there.')
end
end

我知道这很愚蠢,但你能建议我一些可能有效的改变吗?

谢谢!

4

5 回答 5

4
def explaination_exists
  return if (1..4).any?{|i| send("explaination#{i}").length > 5}
  errors.add(:base, "Atleast one explanation should be there.")
end
于 2013-08-17T12:52:19.617 回答
3

这是我的快速尝试:

def explanation_exists
    return true if [explanation1, explanation2, explanation3, explanation4].map(&:length).any? { |length| length > 5}
    errors.add(:base, 'Atleast one explanation should be there.')
end
于 2013-08-17T12:46:38.023 回答
0
def explanation_exists
  [:explanation1, :explanation2, :explanation3, :explanation4].inject(false) do |result, method|
    result || (self.send(:method).length > 5)
  end
end
于 2013-08-17T12:47:01.777 回答
0
def explaination_exists
  return true if %w{ explanation1 explanation2 explanation3 }.map do |exp|
                self.send("#{exp}").length > 5
              end.detect { |e| e }

  errors.add(:base, 'Atleast one explanation should be there.')
end
于 2013-08-17T12:51:41.837 回答
0

我会把它分开一点,比如:

def explanations
  [explanation1, explanation2, explanation3, expanation4]
end

def explanation_exists
  errors.add(:base, :explanation) unless explanations.any? { |e| e.length > 5 }
end

并将错误消息放在activerecord.errors.models.<your-model-name>.attributes.base.explanation(IIRC)下的语言环境中。

于 2013-08-17T19:59:20.813 回答