这是代码:
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
我想将代码缩减为单行代码,因为除了解释[number]之外没有任何变化。
我试过这个:
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
我知道这很愚蠢,但你能否建议我做一些可行的改动。
谢谢!
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分:0)
def explanation_exists
[:explanation1, :explanation2, :explanation3, :explanation4].inject(false) do |result, method|
result || (self.send(:method).length > 5)
end
end
答案 3 :(得分: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
答案 4 :(得分: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)下的语言环境中。